开发者

C++ subclass that derives from classes that derive from the same class

开发者 https://www.devze.com 2023-02-02 08:05 出处:网络
Why is the following inheritance structure not legitimate in C++? Son1 derives from Father1 Son2 derives from Father1

Why is the following inheritance structure not legitimate in C++?

If there could be a case where this is legitimate (perhaps if all classes are pure-virtual except for GrandSon1), what are they and how come?


You are wrong, this is perfectly legal in C++. You might look into virtual inheritance though.


This inheritance hierarchy is called the diamond of death and it’s legal in C++ if you use virtual inheritance, although it’s usually still problematic.


This is the C++ Diamond Problem.

See: http://en.wikipedia.org/wiki/Diamond_problem


This is the typical inheritance diamond. It occurs even in the standard library where iostream derives from both istream and ostream and both of these derive from ios_base.

There are various issues:

  • If Father has a virtual method and both Son1 and Son2 implement it, unless Grandson implements it too it has to state which of Son1 and Son2's methods it implements.

  • If Father has any data members, Grandson would get them twice.

  • In any case Father has a v-table so you seem to get 2 copies of that.

The middle classes therefore usually use virtual inheritance, which is tricky, but effectively means only the final class gets the base class. So in this case Grandson itself is responsible for constructing Father and is assumed to "have" it.

There are further issues to beware of if you are going to cast any pointers. Particularly be careful with casting to and from a void*.


Me think you are confusing class hierarchy and class instance.

a "grandson" class can derived from a "son" class, but an instance of a "grandson" cannot be from 2 instances of the class "son"

In any cases, I think you should not do it like that because at some point you will have a class "grand-grandson" and a class "grand-grand-grandson".

Make the relation ship between parents and siblings in another way.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号