Jump to content
  • Advertisement
Sign in to follow this  
lord_balron

Object Creation

This topic is 3623 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

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!

Share this post


Link to post
Share on other sites
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!