In C++, we use terms abstract class and interface interchangeably. A class with pure virtual function is known as abstract class. For example the following function is a pure virtual function:
virtual void fun() = 0;
A pure virtual function is marked with a virtual keyword and has
= 0 after its signature. You can call this function an abstract function as it has no body. The derived class must give the implementation to all the pure virtual functions of parent class else it will become abstract class by default.
Why we need a abstract class?
Let’s understand this with the help of a real life example. Lets say we have a class
Animal, animal sleeps, animal make sound, etc. For now I am considering only these two behaviours and creating a class Animal with two functions
sound() and
sleeping().
Now, we know that animal sounds are different cat says “meow”, dog says “woof”. So what implementation do I give in
Animal class for the function
sound(), the only and correct way of doing this would be making this function pure abstract so that I need not give implementation in Animal class but all the classes that inherits Animal class must give implementation to this function. This way I am ensuring that all the Animals have sound but they have their unique sound.
The same example can be written in a C++ program like this:
Abstract class Example
#include<iostream> using namespace std; class Animal{ public: //Pure Virtual Function virtual void sound() = 0; //Normal member Function void sleeping() { cout<<"Sleeping"; } }; class Dog: public Animal{ public: void sound() { cout<<"Woof"<<endl; } }; int main(){ Dog obj; obj.sound(); obj.sleeping(); return 0; }
Rules of Abstract Class
1) As we have seen that any class that has a pure virtual function is an abstract class.
2) We cannot create the instance of abstract class. For example: If I have written this line
Animal obj; in the above program, it would have caused compilation error.
3) We can create pointer and reference of base abstract class points to the instance of child class. For example, this is valid:
Animal *obj = new Dog(); obj->sound();
4) Abstract class can have constructors.
5) If the derived class does not implement the pure virtual function of parent class then the derived class becomes abstract.