# To "new" or not to "new"?

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

## 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();

obj1.print();
obj2.print();
obj3->print();

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 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 on other sites
The first two only exist while in a scope.

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

##### 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 on other sites
Quote:
 Original post by C-JunkieThe 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.
[/edit]

##### Share on other sites
Damn, I blink and my question is answered [grin] Awesome. Thanks people.

1. 1
Rutin
24
2. 2
3. 3
4. 4
JoeJ
18
5. 5

• 14
• 14
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
631757
• Total Posts
3002142
×