Summary: In this tutorial, we will learn pure virtual function and abstract class in C++ with examples.

Recommended: C++ Virtual Function

Pure Virtual Function in C++

Pure Virtual function is a function in C++ that is declared as virtual, has nobody, and whose declaration ends with =0.

Example:

Abstract Class in C++

Abstract class is a class that contains at least one pure virtual function.

An abstract class cannot be instantiated i.e. its object cannot be created.

Hence to make use of abstract class we need to inherit it into some other class.

Example:

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

What is the Use of Abstract Class?

An abstract class is useful in case of inheritance.

If an abstract class is inherited by some other class, then it is necessary for the derived class to give implementation (i.e override) for the pure virtual function of the base class (which is Abstract), otherwise derived class will also become abstract. And as a result, the derived class also cannot be instantiated.

Hence, an abstract class is used mainly to create a general class, which can be reused to create more specific classes with different implementation details.

E.g. For creating SavingAccount and CurrentAccount class in C++, it will be best to first create an Abstract Account class then use it for creating different types of accounts by providing the implementation of pure virtual functions of Account Class.

Example: In this example, the Account class is an abstract class and is inherited by other classes.

Output

Abstract Class Program

In the above example, SavingAccount overrides the withdraw() method of the Account class to provide its own implementation.

In this tutorial, we learned about C++ pure virtual function and C++ abstract class.

Leave a Reply