2

AFAIK, Virtual inheritance solves the diamond problem but what if I use virtual to simply inherit from base class? Whats the difference with using virtual here?

class A 
{
    /* ... */
};

class B : virtual public A
{
    /* ... */
};

1 Answer 1

2

There are a few differences. The object layout will be different (in the case of virtual inheritance there will be an extra hidden pointer to the base in the derived subobject), initialization of the subobjects will differ (a type deriving from B will have to call the A constructor directly in the initialization list). Any code in B member functions that refers to A members (data or functions) will require an extra indirection (through the pointer mentioned before), and possibly other differences.

Virtual inheritance is a complex matter and you should probably read more of the links provided in the answers to the previous question of yours than try to understand it by just getting bits and pieces from separate questions.

Hint: If you want to understand the details of how virtual inheritance is handled by the compiler, you should focus on the memory layout of the objects. Once you understand why the extra pointer per class that virtually derives is needed, the rest is simple.

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.