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)?
};
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With