When do we make virtual function “pure"? What are the implications of making a function a pure virtual function?

Subject Object Oriented Programming
NU Year Set: 5.(c) Marks: 2+2=4 Year: 2010

When the class in which it is declared is intended to be abstract (meaning it must be derived from, it cannot be instantiated by itself), and where the derived class is expected to provide an implementation for the method even if the base class has its own implementation. Derived classes that do not fully implement all the pure-virtual methods of their base class become abstract themselves. However, derivatives inherit the sum of all pure-virtual implementations from their base classes, other than from those that initially declared the pure-virtual methods.

 

Only class instance methods can be rendered as pure-virtual functions (or pure-virtual methods, to be precise). Non-member functions and static member methods cannot be declared pure-virtual.

The implication of declaring a pure-virtual function is that the class to which it is a member becomes an abstract data type (or abstract base class). This means you cannot instantiate an object of that class, you can only derive classes from it. Moreover, the derived classes must also implement the pure-virtual functions or they, too, become abstract data types. Only concrete classes that contain a complete implementation can be instantiated, although they can inherit implementations from their base classes (but not from the class that initially declared the method).

Pure-virtual functions ensure that you do not instantiate base class objects that are not intended to be instantiated (they are conceptual rather than actual objects) and that derived objects provide a specific implementation. Typically, all methods of an abstract base class will be declared pure-virtual to ensure correct behaviour in derived classes through a common interface. Abstract base classes will also have few member variables, preferably none at all.

Login to post your comment.