Summary: In this tutorial, we will what pure virtual function and abstract class are and why we use them in the C++ programming language.

Prerequisite: Virtual Function

Introduction to Pure Virtual Function and Abstract Class

A virtual function whose declaration ends with =0 and has no body is called a pure virtual function.

Example:

A class that contains at least one pure virtual function is called an abstract class.

Example:

Note: If a class contains only pure virtual functions, then it acts as an interface.

It is important to note that abstract class cannot be instantiated (i.e. its object cannot be created).

To use the functions and qualities of the abstract class we need to inherit it in another class.

What is the use of the Abstract Class?

If an abstract class is inherited by some other class, then it is necessary for the derived class to provide the implementation (i.e, override) for its pure virtual functions, otherwise, the derived class will also become abstract and as a result, the derived class also cannot be instantiated.

Therefore, an abstract class is mainly used as a common class to create a more specific class with different implementation details.

For example, If we want to create SavingAccount and CurrentAccount class in C++, it will be best to first create an abstract Account class that will provide the general details and functionality such as balance, withdrawal and deposit, etc which is common in both classes. Then inherit it to create a variety of accounts by providing the implementation of pure virtual functions present in the Account Class.

C++ Example: Abstract Class and Pure Virtual Function

Here is a C++ example, where we create an abstract Account class and inherit it to create different types of classes:

Output:

Abstract Class Program

In the above example, we are overriding the withdraw() method of the Account in the SavingAccount to provide its implementation and call the same after creating an object in the main method.

Conclusion

Pure virtual function is a virtual function that ends with = 0 and has no body.

A class must contain at least one pure virtual function to become abstract.

We cannot create an object of an abstract class, rather we inherit it in another concrete class to use its properties and functions.

Leave a Reply

3 × 3 =