Interfaces in c++

interfaces in c plus plus

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:

  1. Abstract class
  2. 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    
    virtual void draw()=0;    
 class Rectangle : Shape    
     void draw()    
        cout < <"drawing rectangle..." < <endl;    
class Circle : Shape    
     void draw()    
        cout <<"drawing circle..." < <endl;    
int main( ) {  
    Rectangle rec;  
    Circle cir;  
   return 0;  


drawing rectangle...
drawing circle...

Rules of Abstract Class

  1. As we have seen that any class that has a pure virtual function is an abstract class.
  2. We can create pointer and reference of base abstract class points to the instance of a child class.
  3. An abstract class can have constructors.
  4. If the derived class does not implement the pure virtual function of the parent class then the derived class becomes abstract.

0 0 vote
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x