Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you inherit the same class twice?

Tags:

c++

Can you inherit the same class twice? E.g. :

class Base {

};

class Foo : public Base {

};

class Bar : public Base {

};

class Baz : public Foo, public Bar { 
    //is this legal? 
    // are there restrictions on Base 
    //       (e.g. only virtual methods or a virtual base)?

};
like image 373
chacham15 Avatar asked Apr 22 '14 22:04

chacham15


1 Answers

Yes it is legal, and no there are no restrictions on Base.

You should however be aware that this causes two different objects of type Base to exist within Baz, which will require you to use qualified names to tell C++ which version of Base you mean, when you try to access its members.

C++ provides a mechanism called virtual inheritance to solve this problem (if it is a problem for you):

class Base { };

class Foo : public virtual Base { };

class Bar : public virtual Base { };

class Baz : public Foo, public Bar { };

This will share the Base object between the Foo and Bar objects within Baz

like image 160
gha.st Avatar answered Sep 18 '22 07:09

gha.st