Sign in to follow this  

To "new" or not to "new"?

Recommended Posts

Ok, so if I have some class, I can declare instances with or without new and then I can use them all just fine: Suppose class "Object" with some "print" function. I can do this:
Object obj1;
Object obj2(someArgument);
Object* obj3 = new Object();


delete obj3;

Basically, the question is, what's the difference (if any)? I can't find a straight answert to this, so I played with it and my understanding that if you don't use the new, you're still allocating space for the object, you just don't have ability to explicitly delete it. Does that sound right? Any other differences between the two ways of instantiation? I usually use the first or second method for objects that will last throughout the program, and the "new" for something that may come and go, so I can delete it if/when I need to. Does that sound right? Or this some general "rule" to this I missed in class? Thanks

Share this post

Link to post
Share on other sites
When you're using new, you decide when that space is allocated. If you will need a maximum of space for 300 models, if you statically declare those variables, you'll always be taking up that space required by the 300 models. If you dynamically allocate that space, you'll be able to use up significantly less. This is also very useful when you don't know how much of something you'll need.

Share this post

Link to post
Share on other sites
Using new to dynamically allocate the memory you need, you are storing data on the heap, rather than on the stack which is limited.

Share this post

Link to post
Share on other sites
Original post by C-Junkie
The first two only exist while in a scope.

for(;;) {
int i;
// i doesn't exist anymore.

This is the most essential difference. You cannot create objects on stack (other than in global scope) that need to be shared among different modules and exist outside the creator's scope.

Another important difference is life-time control.
With objects created using 'new' you decide when the destructor is called and memory is freed (though you can manually call the destructor of obj1 and obj2, this will not free the memory taken up by them).

Objects that require a big amount of memory also benefit from being new'ed - the stack size defined by the compiler might not be able to hold them.

Share this post

Link to post
Share on other sites

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