When might multiple inheritance be the only reason

2020-06-12 04:28发布

To be clear, I'm not asking if/why multiple inheritance is good or bad. I've heard a lot of arguments from both sides of that debate.

I'm wondering if there is any kind of design problem or scenario in C++ in which multiple inheritance is either the only way to accomplish something, or at least is the most optimal way over all other alternatives to the point that it wouldn't make sense to consider anything else.

Obviously, this question doesn't apply to languages that don't support multiple inheritance.

10条回答
闹够了就滚
2楼-- · 2020-06-12 04:45

There is a situation in which you would inherit from a class and maybe implement one or two interfaces in Java. This is something you would resolve with multiple inheritance in c++ I think.

查看更多
老娘就宠你
3楼-- · 2020-06-12 04:55

You can't do policy-based design without multiple inheritance. So if policy-based design is the most elegant way to solve your problem, than that means you need multiple inheritance to solve your problem, over all other options.

Multiple-inheritance can be very useful if it's not misused (like everything, in any language).

查看更多
够拽才男人
4楼-- · 2020-06-12 04:56

As have been said on the other answers:

But also:

查看更多
该账号已被封号
5楼-- · 2020-06-12 04:57

C++ streams use multiple inheritance: istream and ostream are both parents of iostream. Since they both inherit from ios_base, you have a diamond.

It's the only "reasonable" solution in the sense that it would be unreasonable for the streams part of the standard libraries to take the same line as the algorithms and collections. So ostream behaves polymorphically rather than being a "duck-typed" interface like Iterator(*).

As soon as you have dynamic polymorphism, you need multiple inheritance to implement more than one interface at the same time.

(*) Presumably this is because anything else would be a shambles. You have to be able to write actual functions which manipulate streams, rather than forcing users to have templates everywhere. This is because it's common to write to "some stream, I don't know what until runtime", but not to want to manipulate "some collection, I don't know what until runtime".

查看更多
登录 后发表回答