To "new" or not to "new"?

Started by
4 comments, last by dominicoder 19 years, 4 months ago
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
Advertisement
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.
Disclaimer: "I am in no way qualified to present advice on any topic concerning anything and can not be held responsible for any damages that my advice may incurr (due to neither my negligence nor yours)"
The first two only exist while in a scope.

for(;;) {
int i;
}
// i doesn't exist anymore.
Using new to dynamically allocate the memory you need, you are storing data on the heap, rather than on the stack which is limited.
Quote: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.

[edit]
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]

Damn, I blink and my question is answered [grin] Awesome. Thanks people.

This topic is closed to new replies.

Advertisement