Virtuals in C++

The following example shows the use of a virtual in C++. The function Get_Label() is defined in Parent as a virtual. It is given a default implementation for objects of class Parent. This will be used if objects of class Parent are created.

Another version of Get_Label() is provided for the derived class Child. This will now replace the implementation in Parent for any objects of class Child created.

In the example, Get_Label() is called directly for a Child object, but through a pointer of class Parent. It is then called indirectly through invoking the function Print_Label(), which is a static function declared in class Parent. This is done for both a Parent and a Child object.

The calls cause the current string pointed to by label to be printed in the cases involving Child objects, showing that the virtual definition is being used, even by Print_Label(), which is declared in the Parent class.

The access to a Parent object results in the output "No label to return", which is the definition in Parent.

The same program without the virtual specifier outputs "No label to return" in all three cases, showing that the use of a Parent level reference has caused its version to be used. This is as we would expect in a case of static binding.

An example using a virtual function

#include<iostream.h>

class Parent {
protected:
   char* label;
public:
   Parent(char* L);
   virtual  char* Get_Label();
   void Print_Label();
};

Parent::Parent(char* L){ label = L; }
char* Parent::Get_Label() { return "No label to return"; }
void Parent::Print_Label(){ cout<Get_Label() << '\n';
   P->Print_Label();
   Pp->Print_Label();
   return 0;
}


Pure virtuals

The use of a default virtual implementation in the parent class is not necessary. Instead a pure virtual can be specified by giving an inline definition as equal to zero, as follows.

class Parent {
protected:
   char* label;
public:
   Parent(char* L);
   virtual  char* Get_Label() = 0;
   void Print_Label();
};

In this case no objects can be generated from this class. It is purely used as a super-class from which to derive sub-classes, which must provide an implementation if objects are to be derived from them


Next note in series

Back to index