Virtual Functions in C++

Object oriented programming is a style of programming that requires that functionality be attached to objects, instead of freely available through functions. C++, although not being a pure object oriented language, supports the notion of objects and classes of objects.

One of the big advantages of programming with objects is that they can behave differently based on who the messages are sent to. This kind of dynamic behavior is called polymorphism, and is implemented in C++ by the virtual function mechanism.


What is a virtual function?

A virtual function is a member of a class that can be overriden by a derived class to provide different functionality.

For example, a member function draw can be used to determine how a graphical object is drawn on the screen. Depending on the concrete type of the object, however, the shape of the object may change, and the way it is drawn will be different. The function draw in this case is a candidate to be implemented as a virtual function, which will have different implementations for each of the concrete classes.


Creating virtual functions in C++

A virtual function can be created in C++ with the use of the virtual keyword before the declaration of the member function. For example:

class Button {
  virtual void draw() {
    // drawing a generic button
  }
};

class RoundButton {
  virtual void draw() {
    // draw button with a different shape
  }
}