Friday 2 June 2017

Order of Constructor Call in C++ ~ GNIITHELP

Order of Constructor Call

Base class constructors are always called in the derived class constructors. Whenever you create derived class object, first the base class default constructor is executed and then the derived class's constructor finishes execution.

Points to Remember

  1. Whether derived class's default constructor is called or parameterised is called, base class's default constructor is always called inside them.

  2. To call base class's parameterised constructor inside derived class's parameterised constructo, we must mention it explicitly while declaring derived class's parameterized constructor.

Base class Default Constructor in Derived class Constructors


class Base
{ int x;
  public:
  Base() { cout << "Base default constructor"; }
};

class Derived : public Base
{ int y;
  public:
  Derived() { cout << "Derived default constructor"; }
  Derived(int i) { cout << "Derived parameterized constructor"; }
};

int main()
{
 Base b;        
 Derived d1;    
 Derived d2(10);
}
You will see in the above example that with both the object creation of the Derived class, Base class's default constructor is called.

Base class Parameterized Constructor in Derived class Constructor

We can explicitly mention to call the Base class's parameterized constructor when Derived class's parameterized constructor is called.
class Base
{ int x;
  public:
  Base(int i)
  { x = i;
    cout << "Base Parameterized Constructor";
  }
};

class Derived : public Base
{ int y;
  public:
  Derived(int j) : Base(j)
  { y = j;
    cout << "Derived Parameterized Constructor";
  }
};

int main()
{
 Derived d(10) ;
 cout << d.x ;    // Output will be 10
 cout << d.y ;    // Output will be 10
}

Why is Base class Constructor called inside Derived class ?

Constructors have a special job of initializing the object properly. A Derived class constructor has access only to its own class members, but a Derived class object also have inherited property of Base class, and only base class constructor can properly initialize base class members. Hence all the constructors are called, else object wouldn't be constructed properly.

Constructor call in Multiple Inheritance

Its almost the same, all the Base class's constructors are called inside derived class's constructor, in the same order in which they are inherited.
class A : public B, public C ;
In this case, first class B constructor will be executed, then class C constructor and then class A constructor.

No comments:

Post a Comment