Pure Virtual Functions in C++/OOP
- What are Pure Virtual Functions in C++?
- Abstract Classes in C++
- Uses of Abstract Classes
- Syntax of Pure Virtual Functions
- Programming Example
- 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:
- The keyword virtual at the start of the function declarator.
- 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.
virtual void show()=0;
class Child1:public Parent
class Child2:public Parent
Output of the program
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: