is multiple inheritance a compiler writers problem? - c++
i have been reading about multiple inheritance
What is the exact problem with mul开发者_如何学Pythontiple inheritance? http://en.wikipedia.org/wiki/Diamond_problem
http://en.wikipedia.org/wiki/Virtual_inheritance
http://en.wikipedia.org/wiki/Multiple_inheritanceBut since the code does not compile until the ambiguity is resolved, doesn't this make multiple inheritance a problem for compiler writers only? - how does this problem affect me in case i don't want to ever code a compiler
If you want to write code that compiles, you have to know what kind of problems might cause it to not compile and how to avoid these situations. It is your problem, as a user of the compiler, to design your inheritance hierarchies in a way that they will be compilable.
Also if you don't understand how multiple inheritance works you might have wrong assumptions about what exactly your classes do. If classes behave differently than you expect it will cause bugs when you try to use them.
The compiler writer will print a nasty error message and stop compiling your code if you have an unresolved ambiguity due to multiple inheritance. When they say that the code won't compile until the ambiguity is resolved, there are several issues for you to consider:
- You don't have a working program until the ambiguity is resolved.
- The compiler doesn't resolve it for you.
- Therefore, until you resolve it, it's your problem, not the compiler writer's.
No, its not a problem for a compiler writer:
- In general a compiler writer might be defining how multiple inheritance works.
- Specifically for C++, there are several solutions for the writer to implement.
It is a problem for the C++ programmer, but only if you don't understand how MI works in C++.
I have one general solution which is to have a base class which defines a public interface - which you then think of as having distinct subsections, which you then implement as distinct abstract classes, which are multiply inherited by a concrete leaf class:
------
| Base |
------
| |
------
^
|
-----------------
| | |
------ ------ ------
| A | | B | | C |
------ ------ ------
| | | | | |
------ ------ ------
^ ^ ^
| | |
-----------------
|
-------
|Derived|
-------
| |
-------
Each of A, B and C implement non-overlapping subsections of Base, which means you can swap out, say A, for A' for an alternate or improved implementation without affecting any other class.
In general, yes, you hit the nail on the head. It significantly increases the complexity and effort involved in maintaining the compiler, but for the programmer, it only adds a small amount of additional complexity, mostly related to having to be tediously specific if a diamond problem arises. (Which should be very rare in a well-designed object hierarchy.)
精彩评论