lital maatuk
lital maatuk

Reputation: 6249

When is the constructor called?

In which of the following is the constructor of myClass called?

1.  myClass class1;
2.  myClass* class1;
3.  myClass* class1 = new myClass;

Thanks a lot

Upvotes: 22

Views: 18850

Answers (5)

harper
harper

Reputation: 13690

  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 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.

Upvotes: 6

Mark Loeser
Mark Loeser

Reputation: 18657

In both #1 and #3 since you are actually making an instance of the object. In #2 you are merely declaring a pointer that doesn't point to an instance.

Upvotes: 5

Judge Maygarden
Judge Maygarden

Reputation: 27613

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

Upvotes: 1

Daniel Daranas
Daniel Daranas

Reputation: 22644

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

Upvotes: 1

tdobek
tdobek

Reputation: 1186

  1. Yes - default constructor, instance created on stack
  2. No
  3. Yes - default constructor, instance created on heap

Upvotes: 39

Related Questions