I am getting the compiler error C2259
when instantiating a class that inherits from other classes, which having abstract methods.
The inheritance scheme is a little bit weird and opaque but I need to do it in this way due to some restrictions of the problem.
The inheritance scheme is as follow:
class A
{
public:
enum Animal { CAT, DOG };
enum Color { RED, GREEN };
enum Food { MEAT, FISH };
protected:
virtual Animal animal() const = 0;
virtual Color color() const = 0;
virtual Food food() const = 0;
};
class B: public A
{
Animal animal() const { return CAT; }
};
class C: public A
{
Color color() const { return GREEN; }
};
class D: public A
{
Food food() const { return FISH; }
};
And then I declare a class with multiple inheritance like this:
class E : public B, public C, public D
{
};
Here, when I try to instantiate the class E
I am getting the compiler error C2259
:
error C2259: 'E': cannot instantiate abstract class
note: due to following members:
note: 'A::Color A::color(void) const': is abstract
note: see declaration of 'A::color'
note: 'A::Food A::food(void) const': is abstract
note: see declaration of 'A::food'
note: 'A::Animal A::animal(void) const': is abstract
note: see declaration of 'A::animal'
What I am doing wrong?
Thank you very much
Javier
You have 3 different A
objects inside E
, you forgot to tag the inheritance as virtual so that the same A
object is used:
class A
{
public:
enum Animal { CAT, DOG };
enum Color { RED, GREEN };
enum Food { MEAT, FISH };
virtual ~A(){}
protected:
virtual Animal animal() const = 0;
virtual Color color() const = 0;
virtual Food food() const = 0;
};
class B: public virtual A
{
Animal animal() const override { return CAT; }
};
class C: public virtual A
{
Color color() const override { return GREEN; }
};
class D: public virtual A
{
Food food() const override { return FISH; }
};
class E : public B, public C, public D
{
};
int main()
{
E e;
}