Our problem from inheritance is that we can’t access members of a derived object if the pointer pointing to it is of a base type.

Rectangle *r1;
Polygon p;
r1 = &p; // error

The solution is a virtual function, via the virtual keyword. If a function is declared as a virtual function in the base class, and re-defined or overwritten in the derived class, then a call to that function via a base class pointer will invoke the function depending on the type of the object.

class Polygon {
	protected:
		int width, height;
	public:
		void set(int w, int h) {
			width = w;
			height = h;
		}
		virtual int area() { return 0; }
}
 
p1->area(); // invoke the area function of what p1 is pointing to

Non-virtual functions are invoked depending on the type of pointer, known at compile-time. Virtual functions are invoked depending on the type the pointer points to, known ad run-time.

A class that inherits a virtual function is called a polymorphic class.

Extensions

Objects of the base class may sometimes never be intended to be instantiated and only serve to derive other classes. We can enforce pure virtual methods that don’t have a definition by default, so any derived class should re-define.

public:
	virtual double area() = 0;

A class with one or more pure virtual functions is called an abstract class, because objects of these classes cannot be instantiated. They’re also sometimes called interfaces, because they force derived classes to define the virtual function they inherit.