Question

I am trying to do something I haven't really done before. I basically have 3 classes. Class A is an abstract class with pure virtual methods, Class B is a class on it's own that contains methods with the same name as the virtual methods in Class A. I'm trying to tie everything together in Class C. I'd like to inherit class B and A in C (multiple inheritance), and use the methods from Class B to implement those in class A. This way I create a modular approach. The example below is a very simplified version of my code.

class A {
virtual int methodA() = 0;
virtual int methodB() = 0;
virtual int methodC() = 0;
};

class B { //B implements A.A() and A.B()
int methodA() { return 0; }; 
int methodB() { return 0; };
};

class C : A, B {
int methodC() { return 0; }; //C implements A.C()
};

I can compile class C but when I try construct a class of C new C() I get a compiler message saying "cannot instantiate abstract class due to following members: int methodA()' : is abstract".

Is there a way to implement class A using class B through multiple inheritance in class C?

Edit: The wish is to keep class B concrete.

Était-ce utile?

La solution

You can do it with some method-by-method boilerplate.

class A {
public:
virtual int methodA() = 0;
virtual int methodB() = 0;
virtual int methodC() = 0;
};

class B { //B implements A.A() and A.B()
public:
int methodA() { return 0; }; 
int methodB() { return 0; };
};

class C : public A, public B {
public:
int methodA() { return B::methodA(); }
int methodB() { return B::methodB(); }
int methodC() { return 0; }; //C implements A.C()
};

Demo: http://ideone.com/XDKDW9

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top