Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is the constructor called?

Tags:

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

like image 711
lital maatuk Avatar asked Feb 08 '11 15:02

lital maatuk


People also ask

In which situation constructor is called?

Constructor is a special member function of a class which is called/invoked when the object is created. It has the same name as that of a class. Ashish Bardiya said: (Jul 3, 2013) Constructor is call when an object is created or initialize.

How are constructor called?

The constructors can be called explicitly or implicitly. The method of calling the constructor implicitly is also called the shorthand method. Example e = Example(0, 50); // Explicit call. Example e2(0, 50); // Implicit call.

When a constructor is called or invoked?

If members have default constructors or constructor without parameter then these constructors are called automatically, otherwise parameterized constructors can be called using Initializer List. For example, see PROGRAM 1 and PROGRAM 2 and their output.

In which order constructor is called?

For multiple inheritance order of constructor call is, the base class's constructors are called in the order of inheritance and then the derived class's constructor.


2 Answers

  1. Yes - default constructor, instance created on stack
  2. No
  3. Yes - default constructor, instance created on heap
like image 109
tdobek Avatar answered Oct 28 '22 03:10

tdobek


  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.
like image 37
harper Avatar answered Oct 28 '22 04:10

harper