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

>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

Leave a Reply