Abstract Class In C++ (Interfaces)

In C++, abstract classes are used to accomplish abstraction. Abstraction is the process of hiding internal details and displaying only functionality in C++. There are two approaches to create abstraction:

  1. Interfaces
  2. Abstract Class

Both the abstract class and the interface can have abstract methods, which are required for abstraction.

Abstract Class:

In C++, a class is abstracted by declaring at least one of its functions to be pure virtual. In the declaration of a pure virtual function, the keyword “= 0” is used. Derived classes must provide the implementation.

Let’s look at an abstract class in C++ that has only one abstract method: draw (). Rectangle and Circle are two derived classes that implement it. Both classes are implemented differently.

#include <iostream>  
using namespace std;  
class Shape    
{    
    public:   
    virtual void draw()=0;    
};    
 class Rectangle : Shape    
{    
    public:  
     void draw()    
    {    
        cout < <"drawing rectangle..." < <endl;    
    }    
};    
class Square : Shape    
{    
    public:  
     void draw()    
    {    
        cout <<"drawing square..." < <endl;    
    }    
};    
int main( ) 
{  
    Rectangle rec;  
    Square cir;  
    rec.draw();    
    cir.draw();   
    return 0;  
}

Output:

drawing rectangle...
drawing square...

Join Our Community

Join our WhatsApp Group To know more about Programming Language tips, tricks and knowledge about and how to start learning any programming language.

Default image
Lingaraj Senapati
Hey There! I am Lingaraj Senapati, the Co-founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.
Articles: 228

Newsletter Updates

Enter your email address below to subscribe to our newsletter