Yves
Yves

Reputation: 12371

about Multiple inheritance and virtual inheritance

I don't quite understand Multiple inheritance and virtual inheritance. plz help me. Here is my little test:

class Test1
{};

class Test21 : public Test1
{};

class Test22 : public Test1
{};

class Test3 : public Test21, public Test22
{};

int main()
{
    Test1  * t1 = new Test3();
    delete t1;

    system("pause>NUL");
    return 0;
}

I got an error: Error 1 error C2594: 'initializing' : ambiguous conversions from 'Test3 *' to 'Test1 *'.
WHY?

Then I tried like this:

class Test1
    {};

    class Test21 : virtual public Test1
    {};

    class Test22 : virtual public Test1
    {};

    class Test3 : public Test21, public Test22
    {};

    int main()
    {
        Test1  * t1 = new Test3();
        delete t1;

        system("pause>NUL");
        return 0;
    }

Now I got another error: Debug Assertion Failed!

Can someone explain me about Multiple inheritance and virtual inheritance?

Upvotes: 2

Views: 181

Answers (1)

TartanLlama
TartanLlama

Reputation: 65600

Your first piece of code has the exact problem that virtual inheritance solves: you have a diamond in your inheritance hierarchy. Test21 and Test22 both inherit from Test1, so when you inherit from both of them, you actually get two versions of Test1 in your hierarchy, so it is ambiguous as to which one you wish to use.

The solution, is in your second sample: virtually inherit from Test1 so that you just get a single version.

However, your code has undefined behaviour.

Test1  * t1 = new Test3();
delete t1;

You delete a derived instance through a pointer to a base class without a virtual destructor. This means that the Test3 object is not correctly destroyed.

You should add virtual destructors to your classes:

virtual ~Test1() = default; //c++11
virtual ~Test1() {}; //prior version

Upvotes: 1

Related Questions