logo

C++ Keywords - virtual

Used for Runtime polymorphism:

  • the resolving of function call is done at runtime.
  • runtime polymorphism is achieved only through a pointer (or reference) of base class type.
  • not mandatory for the derived class to override.

Pure Virtual Function

A pure virtual function is declared by assigning 0 in declaration. It has no body. Non-pure virtual function may have a default implementation.

virtual void foo() = 0;

Abstract methods in Java is same as pure virtual functions in C++: virtual functions in C++ MAY be overridden, but abstract method MUST be overridden or the class must be abstract too.This is because virtual function have a default implementation and abstract methods have none.

In C++, a class is abstract if it has at least one pure virtual function.

In C++, an interface can be simulated by making all methods as pure virtual.

Virtual Destructor

Rule of thumb: add a virtual destructor (even an empty one) if there's any virtual function in a class.