Base class constructors are always called using 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.
In inheritance constructor of base class is inherited like other member functions. Object of derived class, access the constructor of base class like normal functions.
Example:
class Base
{
int x;
public:
// default constructor
Base()
{
cout<<"Base default constructor\n";
}
};
class Derived:public Base
{
int y;
public:
// default constructor
Derived()
{
cout << "Derived default constructor\n";
}
Derived(int i)
{
cout << "Derived parameterized constructor\n";
}
};
int main()
{
Base b;
Derived d1;
Derived d2(10);
}
Output:
Base default constructor //using object b
Base default constructor // using derived class object d1
Derived default constructor // using derived class object d1
Base default constructor //using derived class object d2
Derived parameterized constructor //using derived class object d2
Note: Using derived class constructor you can supply the argument to the base class constructor. It follows the deriving order in which they are mentioned.
Method of Inheritance | Order of Execution |
Class B:public A | A(); base constructor |
{ | B(); derived constructor |
}; | |
Class A:public B, public C | B(); base constructor(first) |
{ | C(); base constructor(second) |
}; | A(); derived constructor(third) |
Class A:public B, virtual public C | C(); virtual base constructor (first) |
{ | B(); ordinary base constructor(second) |
}; | A(); derived constructor(third) |
You must log in to post a comment.