What is Pure Virtual Function?

Pure Virtual function is a function which is declared as virtual, has nobody and whose declaration ends with  =0. E.g

Abstract Class in C++

An abstract class is a class which contains at least one pure virtual function. And the important point about abstract class is that its object cannot be created. Hence to make use of abstract class we need to inherit it into some other class.

E.g of an abstract class:

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

What is the Use of Abstract Class?

An abstract class is used 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, also its object cannot be created.

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 Saving Account and current Account classes, 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.

Abstract Class Program

Output

Abstract Class Program

That’s all for pure virtual function and abstract class in C++. If you still have any doubt or problem then do comment below.

Leave a Reply

Close Menu