C++Tutorials

Interfaces in c++

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    
{    
    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

  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.

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

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

Check Also
Close
Back to top button