Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Order of constructors

Can someone explain why is the base class constructor is called first ?
I tried a few things but didn’t figure it out

My code:

#include <iostream>

class Base1 {
public:
    Base1() {
        std::cout << "Base1 constructor" << std::endl;
    }
};

class Base2 {
public:
    Base2() {
        std::cout << "Base2 constructor" << std::endl;
    }
};

class Derived : public Base1, public Base2 {
public:
    int x;

    Derived(int val) {
        x = val; // Member variable initialization in constructor body
        std::cout << "Derived constructor" << std::endl;
    }
};

int main() {
    Derived d(42);
    return 0;
}

Would be great if you guys can help me

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The constructor of Base1 is called first because Base1 is the first base class listed in the inheritance declaration of Derived.

You can refer to this question: Order of calling constructors/destructors in inheritance

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading