c++classc++17multiple-inheritancevirtual-inheritance

c++ virtual inheritance doesn't work, how do I use the multiple parents' members?


Example of using virtual inheritance

class AA
{
public:
    AA() { cout << "AA()" << endl; };
    AA(const string& name, int _a):n(name),a(_a) {};
    AA(const AA& o) :n(o.n), a(o.a) {};
    virtual ~AA() { cout << "~AA()" << endl; };
protected:
    int a = 0;
    std::string n;
};

class A1 : public virtual AA
{
public:
    A1(const string& s) : AA(s, 0){}
};

class A2 : public virtual AA
{
public:
    A2(const string& s) : AA(s, 0) {}
};

class B : public A1, public A2
{
public:
    B(const string& a1, const string& a2) : A1(a1), A2(a2){}
    void test()
    {
        cout << A1::n << endl;
        cout << A2::n << endl;
    }
};

void test()
{
    B b("abc", "ttt");
    b.test();
}

Ideally, A1::n would be "abc" and A2::n would be "ttt". But they are both empty. Only AA() will be called once during the entire process.

enter image description here

What did I do wrong?


Solution

  • The result is correct, while the real reason is when you are using virtual inheritance, D ctor first uses AA's default ctor, n is not assigned. If you want to use AA(name, a), you need to explicitly use that in D.