siema
siema

Reputation: 93

A class that inherits from two classes in c++

Assuming that I have got a class Alcohol and it has got two derived classes: Wine and Beer. What happens if I will make then a class Cider that inherits from Wine and Beer as well?

How many copies of Alcohol will appear in Cider class?

I know that it can be done with virtual inheritance and without it but what will be the difference?

Upvotes: 0

Views: 221

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477010

Non-virtual inheritance:

struct Beer : Alcohol {};
struct Wine : Alcohol {};           // I'll have what he's having!
Alcohol   Alcohol                   // ...whe-ere'sh my... bayshe clashhh... hic
   ^         ^
   |         |
 Beer       Wine
    ^       ^
     \     /
      \   /
      Cider

Virtual inheritance:

struct Beer : virtual Alcohol {};   // virtual = doesn't get you drunk
struct Wine : virtual Alcohol {};
     Alcohol                        // you can see clearly now
     ^     ^
    /       \
 Beer       Wine
    ^       ^
     \     /
      \   /
      Cider

In the non-virtual case, there are two disctinct base subobjects. Let's get at them:

Cider x;
Alcohol & a1 = static_cast<Beer&>(x);
Alcohol & a2 = static_cast<Wine&>(x);

assert(std::addressof(a1) != std::addressof(a2));

Upvotes: 13

Related Questions