简体   繁体   中英

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 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.

Since area() in Rectangle is not virtual, it should call area() from Rectangle

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 function vf with the same name, parameter-type-list (8.3.5), cv-qualification, and refqualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual ( whether or not it is so declared ) and it overrides Base::vf .


Side remark. Derividg a square from a rectangle can be problematic as it violates Liskov substitution principle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM