Search code examples
c++inheritance

Initiliazation of members in case of multiple inheritance


I have the following architecture

#include <iostream>

class A_Base {
public:
    A_Base () : foo(14) { }
    
protected:
    int foo;
    // In my real case, A_Base has a lot of members
};

class A_Derived : public A_Base {
public:   
    A_Derived () { foo = 15; }
};

class B_Base : A_Base {
public:
    B_Base() {}
    
    void print_foo () { std::cout << foo << std::endl; } 
    /* B_base has a lots of methods that use A_base members */
};

class B_Derived : public B_Base, A_Derived {
public:
    B_Derived() {}
};

int main()
{
    B_Base bar = B_Derived();
    
    bar.print_foo(); // Prints 14

    return 0;
}

In my real case, A_Base has a lot of members, that are initialized in multiple derived classes. When calling an inherited function from B_Base in B_Derived, I am expecting members intialized in A_Derived to be used. And it appears they are not initialized properly.

So how can I make foo to be intialized at 15 when using B_Derived as a B_Base ?


Solution

  • this is a Diamond Problem and any duplicated base needs to be virtually inherited by its derived class, in this case A_Base is duplicated, therefore all places where it is inherited needs to be marked virtual.

    class A_Base {
    public:
        A_Base () : foo(14) { }
        
    protected:
        int foo;
        // In my real case, A_Base has a lot of members
    };
    
    class A_Derived : public virtual A_Base {
    public:   
        A_Derived () { foo = 15; }
    };
    
    class B_Base : virtual A_Base {
    public:
        B_Base() {}
        
        void print_foo () { std::cout << foo << std::endl; } 
        /* B_base has a lots of methods that use A_base members */
    };
    
    

    online example