Answer to Question #186616 in C++ for Pronoy

Question #186616

Explain the order of execution of constructors in multilevel inheritance using an example.


1
Expert's answer
2021-04-29T18:23:21-0400

The order of execution of constructors in multilevel inheritance is; base class's constructor are executed first followed by execution of derived classes constructors. Given a base class A, class B that inherits from A, and class C that inherits from B:

  • The constructor of class A executes first
  • Then followed by the constructor of class B
  • And lastly, the constructor of class C will execute.

Example

#include <iostream>


using namespace std;


//define class A
class A{
    public:
        //define a default constructor
        A(){
            cout<<"I am in class A"<<endl;
        }
};


//define class B
class B: public A{
    public:
        //define a default constructor
        B(){
            cout<<"I am in class B"<<endl;
        }
};




//define class C
class C: public B{
    public:
        //define a default constructor
        C(){
            cout<<"I am in class C"<<endl;
        }
};


int main()
{
    C c1;


    return 0;
}

Output:


I am in class A

I am in class B

I am in class C


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS