Thursday, July 9, 2009

C++ Programming: If class B2 inherits class B1 as public. Then, if class C tries to inherit both B1 and B2?

If class B2 inherits class B1 as public. Then, if class C tries to inherit both B1 and B2, by multiple inheritance, what would happen? Please explain clearly.

C++ Programming: If class B2 inherits class B1 as public. Then, if class C tries to inherit both B1 and B2?
Then you will be faced with the 'lattuce' problem, that is, for a certain virtual method, the compiler will not know which base class to use (either the left or the right).





Some compilers solve the issue by emitting an error if there is no explicit override of every method that can incurr in this inconvenient.
Reply:Although typically this wouldn't be a practical way of using inheritance, it raises and interesting question about some pitfalls of multiple inheritance.





Scenario:





B and C inherits from A, and D inherits from B and C.





"C++ by default follows each inheritance path separately, so a D object would actually contain two separate A objects, and uses of A's members have to be properly qualified. If the inheritance from A to B and the inheritance from A to C are both marked "virtual" ("class B : virtual A"), C++ takes special care to only create one A object, and uses of A's members work correctly. If virtual inheritance and nonvirtual inheritance are mixed, there is a single virtual A and a nonvirtual A for each nonvirtual inheritance path to A."





http://en.wikipedia.org/wiki/Diamond_pro...





To further clarify:





If A contains foo and B and/or C overrides foo, then you must be explicit when you try to use foo in D and specify which foo to use. If C contains foo2 and A and B does not, then you're still okay to use foo2 in D. You just have to be really careful when overriding.
Reply:Logically, if B2 inherits B1, the B2 should be a superset of B1.





If C is a superset of B2, it should only inherit B2. Otherwise, it should inherit only B1.





(Addendum for cantankerous)





I understand the original question and your answer is relavent. I want people to understand WHY we inherit, not just WHAT HAPPENS if. In both your scenario and the original questions scenario, you need to be asking WHY you would inherit from multiple LIKE objects. And if that si the only way to solve the problem, then care must be taken to qualify like subclasses properly.





That's why I'm such a fan of C# and Java - you can only inherit from one class and implement various inerfaces...

survey

No comments:

Post a Comment