Inheriting both abstract class and class implementation in C++
I hope this is a simple question.
Can I inherit both an abstract class and it's implementation? That is, can the following be made to work?
class A {
virtual void func1() = 0;
}
class B {
void func1() { /* implementation here */ }
}
class C : public A, public B {
}
I've tried a few variations, and am getting compile errors complaining about unimplemented methods in class C. I can save a lot of repeated code if I can make this work, however. Is it possible?
I solved this by creating a "composite class" called D which inherits from A & B开发者_开发知识库, but contains the implementation code previously contained in B. This makes my inheritance model less clean, but it solves the problem without requiring code duplication. And, as I noted in the comments below, it makes my naming conventions pretty gross.
class A {
virtual void func1() = 0;
}
class B {
// Other stuff
}
class D : public A, public B {
void func1() { /* implementation here */ }
}
class C : public D {
}
class B
is not an implementation of class A
in your code. Class B
should be inherited from class A
and func1
should be virtual. Only in that case class B
will be implementation of class A
. And then there is no need to inherit from both A and B.
class A {
virtual void func1() = 0;
}
class B : public A {
virtual void func1() { /* implementation is here */ }
}
class C : public B {
}
Otherwise you will get unimplemented pure virtual function func1
.
Make B inherit from A. If that is not possible, using virtual inheritance might also work (I am not entirely sure about this).
If you want to reuse code from B class in C class, try to do something like this:
class C : public A, public B {
void func1(){ B::func1(); }
}
As Kirill pointed out: Your premise is wrong.
Class B in your example does not inherit class A (it needs to be declared to do that first).
Thus, B.func1() is something entirely different to A.func1() for the compiler. In class C it is expecting you to provide an implementation of A.func1()
Somebody above posted something along the lines of:
class C : public A, public B
{
// implement A::func1()
virtual void func1()
{
// delegate to inherited func1() in class B
B::func1();
}
}
精彩评论