Reputation: 69
// multiple inheritance
#include <iostream>
using namespace std;
class Polygon {
protected:
int width, height;
public:
Polygon (int a, int b) : width(a), height(b) {}
virtual int area()=0;
virtual void print(){
cout << "area = " << area() << endl;
};
};
class Rectangle: public Polygon{
public:
Rectangle (int a, int b) : Polygon(a,b) {}
int area () { return width*height; }
void print(){
cout << "area = " << area() << endl;
};
};
class Square: public Rectangle{
public:
Square (int a, int b) : Rectangle(a,b) {}
int area () { return width*height/2; }
};
int main () {
Square sq (4,5);
sq.print ();
return 0;
}
In this function, print calls area() of Square (not Rectangle). Why? Since area() in Rectangle is not virtual, it should call area() from Rectangle. Final result is 10. According to me it should be 20.
Upvotes: 3
Views: 82
Reputation: 32586
Since
area()
inRectangle
is not virtual, it should callarea()
fromRectangle
It actually is virtual
, since it was declared virtual
in the base class. This attribute is automatically transferred to inherited classes' member function declarations.
See the standard, Virtual functions [class.virtual] (emphasis mine):
If a virtual member function
vf
is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member functionvf
with the same name, parameter-type-list (8.3.5), cv-qualification, and refqualifier (or absence of same) asBase::vf
is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overridesBase::vf
.
Side remark. Derividg a square from a rectangle can be problematic as it violates Liskov substitution principle.
Upvotes: 4