Can you inherit the same class twice?

Can you inherit the same class twice? For instance.

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)?

};
+4
source share
5 answers

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

However, you should be aware that this leads to the fact that Bazthere are two different types of types Basethat require you to use qualified names to tell C ++ which version Baseyou have in mind when trying to access its members.

C ++ provides a mechanism called virtual inheritance to solve this problem (if this 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 divide the object Basebetween objects Fooand BarinBaz

+9

, , , , , ::.

Baz x;
Base& y = x; // Illegal because ambiguous.
Base& y = (Bar&)x; // Now unambiguous.

Base , , Base.subobject.
.

class Base {}
class Foo : public virtual Base {}
class Bar : public virtual Base {}
class Baz : public Foo, public Bar {}

Baz x;
Base& y = x; // Legal, because even though both direct bases inherit from `Base`,
// they do so virtually, thus there is only one Base subobject
Base& y = (Bar&)x; // Still unambiguous.

, Foo , Foo:: Derived Baz ( ) .
, - Bar, .

0

, .

, ( ),

class Base {};
class Foo : public Base {};
class Bar : public Base {};

class Baz : public Foo, public Bar {};

- .

( virtual), - . ++. , . , -, , , . . , – , Java, Java final ( ++ 11).

0
source

It is legal. But restrictions arise when classes are marked as protected and private classes in front of it. For this, its respective functions and attributes are protected and confidential.

0
source

Source: https://habr.com/ru/post/1537589/


All Articles