C++ abstract class
C++ Abstract class
In C++ language, we use terms abstract class and interface interchangeably. Any class with pure virtual functions is known as abstract class. For example the following function is a pure virtual function
A pure virtual function is marked with a virtual keyword or followed by virtual keyword and has = 0 after its signature. we can call this function an abstract function because 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 it’s with the help of a real life example. Lets 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 sleeping() and sound() .
Now, we know that animal sounds are different dog says “woof”, cat says “meow” . So what implementation do I give in Animal class for the function or method sound(), inly the correct way of doing this would be making this function pure abstract so that I do not need give implementation in Animal class but all the classes that inherits Animal class must give implementation to this function. This is the way that all the Animals have sound but they have their unique sound.
The same example can be written in a C++ program like this:
<iostream >
using namespace std;
class Animal
{
:
//Pure Virtual Function
sound() = 0;
sleeping() {
cout<<"Sleeping";
}
};
class Dog: public Animal {
:
sound()
{
cout << "Woof" << endl;
}
};
main()
{
Dog obj;
obj.sound();
obj.sleeping();
0;
}
|