Understanding virtual function
// 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 the call area () of a square (not a rectangle). What for? Since area () in Rectangle is not virtual, it must call area () from Rectangle. The end result is 10. For me, it should be 20.
source to share
Since
area()
in isRectangle
not virtual, it must callarea()
fromRectangle
In fact, thisvirtual
is since it was declared virtual
in the base class. This attribute is automatically wrapped in function declarations of inherited classes.
See the standard, Virtual Functions [class.virtual] (emphasis mine):
If a virtual member function is
vf
declared in class Base and in a class Derived obtained directly or indirectly from Base, a member function ofvf
the same name, parameter list (8.3.5), cv-qualification and refqualifier (or no same) as andBase::vf
, then Derived :: vf is also virtual ( no matter declared ) and it overridesBase::vf
.
Side note. Derivald square from rectangle can be problematic because it violates Liskov's substitution principle.
source to share