[ACCEPTED]-When is the constructor called?-constructor
Accepted answer
- Yes - default constructor, instance created on stack
- No
- Yes - default constructor, instance created on heap
0
In both #1 and #3 since you are actually 3 making an instance of the object. In #2 2 you are merely declaring a pointer that 1 doesn't point to an instance.
- The statement would instatiate an object on the stack, call c'tor.
- Defines only a pointer variable on the stack, no constructor is called.
- The new operator would create an object in free store (usually the heap) and call c'tor.
But this code will not instantiate any object, as 1 it does not compile. ;-) Try this one:
myClass class1;
myClass* class2;
myClass* class3 = new myClass;
- class 1 is a local variable (on the stack), constructor called.
- class 2 is a pointer, no constructor called.
- class 3 is a pointer, the constructor is called, when new is executed.
1 and 3, because in them you create a myClass 1 object.
The constructor is called in cases 1 and 2 3 when a class is instantiated. The other 1 one (2) only declares a pointer.
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.