Sign in to follow this  

Object Creation

This topic is 3317 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 3317 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this