Reputation: 868
I have a virtual inheritance example like below:
class Polygon {
public:
virtual double area() = 0;
};
class Rectangle : public virtual Polygon {
double a, b;
public:
Rectangle(double a, double b) {
this->a = a;
this->b = b;
}
double area() { return a * b; }
};
class Rombus : public virtual Polygon {
double a, h;
public:
Rombus(double a, double h) {
this->a = a;
this->h = h;
}
double area() { return a * h; }
};
class Square : public Rectangle, public Rombus {
public:
Square(double a) : Rectangle(a, a), Rombus(a, a) {}
};
It is one of requirements that Suare has to inherit from Rectangle and Rombus. That's why I use virtual inheritance. But then I got an error:
override of virtual function "Polygon::area" is ambiguous
'Square': ambiguous inheritance of 'double Polygon::area(void)'
What am I doing wrong?
Upvotes: 3
Views: 2474
Reputation: 249642
The error message is:
'Square': ambiguous inheritance of 'double Polygon::area(void)'
It should be obvious why: there are two implementations!
double area() { return a * b; } // in Rectangle
double area() { return a * h; } // in Rhombus
Square
inherits both of them, so there is no possible way the compiler could know which to use.
You can "fix" it by overriding area()
in Square
as well.
This design is deficient from the start: a Square
should only contain a single member, its width/height. But yours contains four members, all of which will always have the same value!
Upvotes: 4