2

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.