Virtual Function and abstract classes

Virtual functions :

  • Virtual functions are used for method overriding or achieve Late Binding.
  • Virtual Keyword is used to make a function Virtual.
  • Virtual keyword will lead to Late Binding of that method
  • If a function is declared as virtual in the parent class, it will be virtual in all its derived classes.
  • A class that declares or inherits a virtual function is called a polymorphic class.
Following examples illustrates the use of virtual functions :

OUTPUT:

Now, the display function of B can be overridden with display() of A or C.
A small definition can be given to the virtual function but outside the class where it is declared.

Pure Virtual Functions :

  • Pure virtual Functions are virtual functions with no definition.
  • Pure Virtual functions can be given a small definition, but, they must be given outside the class in which declared
  • Inline pure virtual definition is illegal.
  • Syntax for a pure virtual function
        virtual void f() = 0;

Abstract Classes

  • Abstract Class is a class which contains at least one Pure Virtual function
  • Classes inheriting an Abstract Class must provide definition to the pure virtual function, otherwise they will also become abstract class.
  • By adding a pure virtual member function to the parent class, you are forced to override member function definition to any derived class.
  • Abstract class cannot be instantiated
  • References and pointers can be created for abstract classes
Following examples illustrate the pure virtual classes :
OUTPUT:

 

Leave a Reply

Your email address will not be published. Required fields are marked *