Sunday, November 20, 2011

C++ Tutorial: Pure Virtual functions and Abstract Class

Normally, when creating class hierarchy with virtual functions, in most of the cases it seems that the base class pointers are used but the base class objects are rarely created. When the objects of base class are never instantiated, such a class is called abstract base class or simply abstract class. To get the full benefit of virtual function, the virtual functions in the base class overridden by the function in the derived class. Usually, base classes are more general class and the base class objects are rarely created when using virtual functions. The base class pointers are used to hold the address of derived class objects and because of virtual function the derived class functions are called when the function are accessed through base class pointer. And,  because the base class objects are rarely created and the base class virtual functions are not called, the base class virtual function can be defined with a null body. To define a virtual with null body ( =0) is written as the function body. A virtual function with a null body is called pure virtual function. The syntax of declaration of pure virtual function and making a class abstract is:
  1: class class_name{
  2:     public:
  3:       virtual return_type function_name = 0;
  4:       //pure virtual function
  5: };

Here class become abstract since there is presence of pure virtual function. The expression =0 does not have any other meaning except the function has a null body. 

Important: If a pure virtual function is not overridden in the derived class, then the inherited pure virtual function remains as it is in derived class. In this case, the object of the derived class cannot be created, so that the derive class will also be an abstract if it does not override the pure virtual function. So, it will again serve as a base for other. So the pure virtual functions must be overridden if the derived class has to be a concrete class.

1 comment:

  1. Thanks good one! Also nice to know that there can be an implementation of a pure virtual function in the base class, as described here:

    C++ Pure virtual function