C ++ Multiple Inheritance - why don't you work?

I am trying to figure out an interesting problem of multiple inheritance.

Grandparents are an interface class with several methods:

class A { public: virtual int foo() = 0; virtual int bar() = 0; }; 

Then there are abstract classes that partially complete this interface.

 class B : public A { public: int foo() { return 0;} }; class C : public A { public: int bar() { return 1;} }; 

The class that I want to use inheritance from both parents, and indicates which method should come from where using directives:

 class D : public B, public C { public: using B::foo; using C::bar; }; 

When I try to create an instance of D, I get errors for trying to create an abstract class.

 int main() { D d; //<-- Error cannot instantiate abstract class. int test = d.foo(); int test2 = d.bar(); return 0; } 

Can someone help me understand the problem and how best to use partial implementations?

+8
c ++ inheritance multiple-inheritance diamond-problem
source share
2 answers

You do not have diamond inheritance. The base classes B and C each D have their own subobject of base class A , since they are not actually inherited from A

So, in D there are four pure virtual member functions that you need to implement: A::foo and A::bar from B and A::foo and A::bar from C

You probably want to use virtual inheritance. Class lists and base class lists will look like this:

 class A class B : public virtual A class C : public virtual A class D : public B, public C 

If you do not want to use virtual inheritance, you need to override two other pure virtual functions in D :

 class D : public B, public C { public: using B::foo; using C::bar; int B::bar() { return 0; } int C::foo() { return 0; } }; 
+13
source share

You need to make the base classes virtual so that they inherit correctly. The general rule is that all infrequent member functions and base classes must be virtual IF you know what you are doing and want to disable normal inheritance for that member / base.

-2
source share

All Articles