Pure Virtual Functions and Abstracts Classes in OOP

Pure Virtual Functions in C++/OOP

Pure Virtual Functions and Abstracts Classes in OOP

Lesson Outlines:

  1. What are Pure Virtual Functions in C++?
  2. Abstract Classes in C++
  3. Uses of Abstract Classes
  4. Syntax of Pure Virtual Functions
  5. Programming Example
  6. How Pure Virtual Function Programs Works?

Pure Virtual Functions 

A type of virtual function that has no body is known as a pure virtual function. A function can be declared as a pure virtual function by adding two things:
  1. The keyword virtual at the start of the function declarator.
  2. The = 0 at the end of the function declarator.
The pure virtual functions are used in the classes which are not used directly. The user can inherit the class and then override the pure virtual function in the child class.

Abstract Classes in C++/OOP

A type of class that contains any pure virtual function is called an abstract class. An abstract class cannot be used directly. It means that no object of an abstract class can be created. However, a child class can inherit an abstract class and use it by overriding its pure virtual function.
The abstract classes are used to create a model class. Any user who creates a new class by inheriting an abstract class has to override the pure virtual function. The child class also become an abstract class if any of the pure virtual functions is not overridden in a child class.

Syntax of Pure Virtual Functions

The syntax of declaring pure virtual function is as follows:
virtual return-type function-name()=0;
Virtual: It is the keyword used to declare a virtual function.
Return-type: It indicates the type of value return by the function.
F-name: It indicates the name of the function.
=0: It indicates that the function is a pure virtual function.

Programming Example:


class Parent
virtual void show()=0;
class Child1:public Parent
void show()
cout<<“Child1 class….”<<endl;
class Child2:public Parent
void show()
cout<<“Child2 class….”<<endl;
void main()
ptr[0]=new Child1;
ptr[1]=new Child2;

Output of the program

Child1 class…
Child2 class…

How above Program Works?

The above program declares an abstract class Parent and two child classes. The child classes override the pure virtual function declared in the parent class.
It is important to declare a pure virtual function in a parent class and override it in all child classes to implement polymorphism.
A Pointer of type Parent will refer to the objects Child1 and Child2 only if these classes are declared as child classes of the Parent class.
You may like:

Virtual Functions in OOP-Early Binding-Late Binding