The former constructs the object in the stack. It's automatically destructed as soon as it goes out of scope.
The latter constructs it in the heap. It's not automatically destructed.
Thank you for the reply. I understand some of what you are saying, but can it be said more "novice-ish"? When do I want to choose the former or latter? What is best for speed or memory usage?
The former way is just an object stored using the automatic memory, the latter can be dynamically allocated as an array of object and/or used to have polymorphism which is a powerful tool
A word of advice from a beginner like you: it is more safe to use Classname Classobject("Value"); because, as helios explained, the program calls the object destructor automatically, which saves you a lot of coding, and is less error-prone. Another advantage:
1 2 3 4 5 6 7 8 9 10 11 12
Classname* Classobject= new Classname[10]();
delete Classobject;//incorrect will cause a memory leak
delete [] Classobject;//correct
Classobject= new Classname();
delete [] Classobject;//this will crash
delete Classobject;//correct
Classobject= new Classname[1]();
delete Classobject;//incorrect
delete [] Classobject;//correct
while you don't have to worry for such things when using the first style:
1 2
Classname Classobject[10]; //will call all 10 destructors
//automatically when the object expires: correct me if I am wrong!
Just a couple of corrections: delete Classobject;
This doesn't cause the program to crash, but it does leave unfreed memory, so it causes a memory leak.
Classname Classobject[10];
This works only if Classname has a constructor with no parameters.
you are completely right... now a beginners question: why is Classname* Classobject= new Classname[10](); correct, and Classname Classobject[10](); incorrect?
That is, I would like to have a "concept explanation" rather than "this is so because this is so".
*Corrected the syntax in the previous post to be proper
Because new Classname[10](); is unambiguously an allocation, but Classname Classobject[10](); could be an array declaration as well as a function declaration.
They're both incorrect, kind of.... sort off.... not really.
Classname* Classobject= new Classname[10](); compiles -- though I find that a little surprising myself. In any case it's redundant and unnecessary. As soon as you try to call anything but the default ctor with those parenthesis, it will error on you.
Classname* Classobject = new Classname[10]; <---- typical.
EDIT -- or listen to helios. His answer makes more sense. XD
Note that there's no point in the empty parens after the new form. You don't need them and you're not allowed to pass any args anyway.
This Classname Classobject[10]();
is interpretted something like this Classname (*Classobject)();
whereas a proper array of functions might be Classname (*Classobject[10]) ();