[ACCEPTED]-When is the constructor called?-constructor

Accepted answer
Score: 36
  1. Yes - default constructor, instance created on stack
  2. No
  3. Yes - default constructor, instance created on heap

0

Score: 5

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.

Score: 5
  1. The statement would instatiate an object on the stack, call c'tor.
  2. Defines only a pointer variable on the stack, no constructor is called.
  3. 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.
Score: 1

1 and 3, because in them you create a myClass 1 object.

Score: 1

The constructor is called in cases 1 and 2 3 when a class is instantiated. The other 1 one (2) only declares a pointer.

More Related questions