1

I understand that a Virtual Function is a function that can be redefined in classes that inherit that function.

Yet, I do not understand why I would need a Virtual Function. Can someone explain me or show me cases where I would need Virtual Functions?

Thanks!

xjose97x
  • 41
  • 2
  • 4

2 Answers2

0

There is nice explanation with good example https://en.wikipedia.org/wiki/Virtual_function

Nogi
  • 134
  • 9
0

Any function can be redefined in a class' inheritors. The key to virtual functions is that they are supposed to be overriden.

Suppose you have a polygon class (in C++):

class Polygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
    virtual int area ()
      { return 0; }
};

Now it doesn't make sense to define the Polygon.area function inside the polygon class, because at this level you don't know what the polygon is. The existence of the virtual function enforces all inheritors to implement their own version of the function.

DaveBensonPhillips
  • 3,134
  • 1
  • 20
  • 32