Question: If a derived class object is created, which constructor is called first?
a. Derived class constructor
b. Base class constructor
c. Totally Depends on that how we call the object
d. Both a and B
MCQs Answer:
Base class constructor
Now, let’s see the diagram. The numbers 1, 2, 3, and 4 in the diagram represents a sequence of execution.
The diagram has 3 parts.
- The Left most diagram represents single inheritance
- When the object of the child class creates, then firstly constructor of the base class will execute(represents with 1), and then the child class constructor will execute (represents with 2).
- The central diagram represents Multiple inheritance
- When the object of the child class creates, then firstly constructor of the base classes will execute(represents with 1 and 2 in parent classes), and then the child class constructor will execute (represents with 3).
- The rightmost diagram represents Multilevel inheritance
- When the object of the child class creates, then firstly constructor of the topmost base classes will execute(represents with 1Â in top parent class), and then the constructor of the middle base classes will execute(represents with 2Â in middle parent class), and then the child class constructor will execute (represents with 3).
C++ Program to represents that If a derived class object is created, then which constructor is called first?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
//eg of constructor and destructor in single inheritance #include<iostream> using namespace std; class Parent { public: Parent() { cout<<"The Parent class constructor will execute first."<<endl; } ~Parent() { cout<<"The Parent class destructor will execute second."<<endl; } }; class Child:public Parent { public: Child() { cout<<"The Child class constructor will execute second."<<endl; } ~Child() { cout<<"The Child class destructor will execute first."<<endl; } }; int main() { Child d; return 0; } |
Output
The Parent class constructor will execute first.
The Child class constructor will execute second.
The Child class destructor will execute first.
The Parent class destructor will execute second.
Note: in the case of destructors, the destructor of the child class will execute first and then the destructor of the parent class will execute.