C++

C++ Interfaces: Abstract Classes – Detailed FAQ

The phrases abstract class and interface are synonymous in C++. A class that only has virtual functions is referred to as an abstract class. For instance, the following function is entirely virtual:

virtual void fun() = 0;

A virtual keyword is used to identify a pure virtual function, and its signature includes the notation = 0. Given that this function has no body, you can classify it as an abstract function. All of the parent class’s pure virtual functions must be implemented by the derived class; otherwise, it will automatically become an abstract class.

Why we need a abstract class?

Let’s use a real-world example to assist us comprehend this. Let’s imagine that our class is called Animals. Animals sleep, create noise, etc. I’m only focusing on these two behaviors for the time being, thus I’ve created a class called Animal having the functions sound() and sleeping ().

We now understand that animal noises vary. Dog says “woof,” as the cat meows. So how do I implement the function sound() in the Animal class? The only way to do this correctly is to make the function pure abstract, which eliminates the need for me to implement the function in the Animal class and instead requires all classes that derive from the Animal class to implement the function. By doing this, I can guarantee that each animal has a distinct sound while still having sound at all.

The identical example can be expressed in a C++ program as follows:

Abstract class Illustration

#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;
}

Abstract Class Rules

1) As we’ve seen, an abstract class is one that has only pure virtual functions.
2) It is impossible to make an instance of an abstract class. For instance, the line Animal obj; in the aforementioned program would have resulted in a compilation error.
3) We can make base abstract class pointers and references that point to instances of child classes. This is true, as an illustration:

Animal *obj = new Dog();
obj->sound();

4) Constructors are possible in abstract classes.
5) The derived class becomes abstract if it does not implement the parent class’s pure virtual method.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button