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

Viewed 72

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?

2 Answers

I was stupid. What virtual inheritance mean is to make the member become one. What I really want is just 2 copies of the members, just eliminate virtual.

class A {
protected:
    int a = 10;
public:
    A(int i):a(i){}
    virtual ~A(){}
};
class A1 : public /*virtual*/ A
{
public:
    A1(int i) :A(i) {};
};
class A2 : public /*virtual*/ A
{
public:
    A2(int i) :A(i) {};
};
class B : public A1, public A2
{
public:
    B(int a1, int a2): A1(a1), A2(a2) {}
    void test()
    {
        cout << A1::a << endl;
        cout << A2::a << endl;
    }
};
void test()
{
    B(1, 2).test();
    cout << sizeof(B);
}

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.

Related