Object Creation

Started by
5 comments, last by lord_balron 15 years, 5 months ago
I was wondering what the major differences between:

Class object;

&

object = new Class();

I see both but don't know what the difference is... Thank you!
Advertisement
That would depend on what programming language you're using.
What language? Also, moved to For Beginners.
This is C++ sorry.
The first one would declare a new instance of Class named object. This instance would be deleted as soon as it goes out of scope (usually when the function returns). The second one creates a new instance of class and place its address in object (assuming object is a pointer). It will not go away until you delete it.


BTW, I recommend that you don't name any of your classes "Class". Even though C++ will let you do this, it can be very confusing to other programmers.
Placeholder for better sig.
If you are using Java, then Class object; declares a variable of type Class with the name object. Since in Java all classes define reference types, object can store a reference to an instance of Class. And since you didn't initialize object explicitly, it gets implicitly initialized to null, the reference that doesn't refer to any instance. The following line object = new Class(); then creates a new instance of Class on the heap and stores a reference to that instance in object.

If you are using C++, then Class object; creates an instance of Class in object without another level of indirection. The following line object = new Class(); then creates a new instance of Class on the heap and stores a pointer to that instance in object, but in this case that wouldn't work because object is declared to be a Class, not a pointer to a Class. You'd have to write Class *object; object = new Class(); for that to work, and that's why I assumed you are using Java.
Thank you, and no I won't be naming it Class, it was just for an example.

This topic is closed to new replies.

Advertisement