Go Down

Topic: Declaring Class Variables / Calling Constructors (Read 3200 times) previous topic - next topic

tamberg

Hi,

(coming from Java, no C/C++ experience)

there seems to be a difference between Processing and Arduino when it comes to calling a constructor to instantiate an object of a class.

E.g. Processing

   C c; // declare variable c
   c = new C(); // create object of class C
   c.M(); // call method M of c

vs. Arduino

   C c(); // declare & create
   c.M(); call method M of c

Now my questions:

1) Is there a way in Arduino to declare a variable of a class and *later* assign an instance to it?

2) Does Arduino really have classes, objects and constructors?

Regards,
tamberg

PaulS

Quote
1) Is there a way in Arduino to declare a variable of a class and *later* assign an instance to it?


No. What you have to do is move the logic that you would put into a constructor into an initialization method, instead (usually called begin).

Quote
2) Does Arduino really have classes, objects and constructors?


Yes. It has objects, but not instances.

tamberg

Thanks for your quick answer. What do you mean by "objects but not instances"? Isn't an object just an instance of a class? Or are Arduino objects rather like structs in C?

Regards,
tamberg

Spinlock

I have to disagree with PaulS.  It does have objects and instances - just not dynamic instances.

that is to say you can't create and delete objects on the fly using C++'s new and delete.

PaulS

Quote
that is to say you can't create and delete objects on the fly using C++'s new and delete.


To me, that's what distinguishes objects from instances. Objects are statically defined, while instances are dynamically defined.

Perhaps not technically accurate (certainly not with using the word static there), but that's the way I think of objects and instances.

AlphaBeta


PaulS

Yes, I know that. I'm struggling to come up with the right terminology to define the difference between object1 and object2 in this scenario:

MyClass object1;
MyClass *object2 = new MyClass();

Since the Arduino can't do the latter, I think of it as not being able to have instances. I guess that's not the right term, but I don't know what the right term to describe object2 is.

Mike Murdock

You could say that the Arduino has instances, but not instantiation ;)

-Mike

AlphaBeta

My (well, not only mine) ideas on the matter:
MyClass object1; //this is in fact instantiation of the class MyClass

MyClass *myObjectReference = &object1; //could use myObjectPointer

Generally one speaks of the latter example as 'A pointer to an instance of class MyClass' or simply 'A pointer' or 'A reference'.  :)

jgrepps

Quote
1) Is there a way in Arduino to declare a variable of a class and *later* assign an instance to it?


tamberg, can you elaborate on this question?  Are you trying to create an instance of an object1 within another class (say...MyClass2).  Then set variables of object1 via a method of object1?

Go Up