Abstract classes are the way to achieve abstraction in C++. Abstraction in C++ is the process to hide the internal details and showing functionality only. Abstraction can be achieved by two ways:
- Abstract class
- Interface
Abstract class and interface both can have abstract methods which are necessary for abstraction.
Why we need an abstract class?
Let’s understand this with the help of a real-life example. Let’s say we have a class, animal sleeps, the animal makes a sound, etc. For now, I am considering only these two behaviors and creating a class Animal with two functions sound()
and sleeping()
.
Now, we know that animal sounds are different cat says “meow”, the 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 inherit 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.
#include <iostream> using namespace std; class Shape { public: virtual void draw()=0; }; class Rectangle : Shape { public: void draw() { cout < <"drawing rectangle..." < <endl; } }; class Circle : Shape { public: void draw() { cout <<"drawing circle..." < <endl; } }; int main( ) { Rectangle rec; Circle cir; rec.draw(); cir.draw(); return 0; }
Output:
drawing rectangle... drawing circle...
Rules of Abstract Class
- As we have seen that any class that has a pure virtual function is an abstract class.
- We can create pointer and reference of base abstract class points to the instance of a child class.
- An abstract class can have constructors.
- If the derived class does not implement the pure virtual function of the parent class then the derived class becomes abstract.
One Comment