Abstract Class in C++ Programming
OOPs in C++
In this lesson, we will understand what is Abstract Class in C++ Programming and how to create them along with some examples.
What is Abstract Class in C++?
An abstract class is a class whose object can't be created but can be used as a base class for other classes.
In C++, an abstract class is defined by including at least one pure virtual function in the class definition. A pure virtual function is a function that has no implementation (function body) and is declared with the notation "= 0".
It can be declared either in the private or public section of the class. We can't create an object of an abstract class because the pure virtual function does not have any implementation (function body).
Example
class Shape
{
public:
virtual double area() = 0;
virtual double perimeter() = 0;
};
In the above example, the Shape class is an abstract class because it contains two pure virtual functions: area and perimeter. If we inherit the Shape class into another class, we must define the body of the two pure virtual functions of the Shape class inside the derived class; otherwise, we will not be able to create an object of the derived class.
Abstract classes are useful for defining interfaces because they allow us to specify a set of functions that must be implemented by any class that derives from the abstract class. They allow us to create a common interface for a group of related classes.
For example, we can create a Circle class that inherits from Shape and implements the area and perimeter functions:
Example
#include <iostream>
using namespace std;
class Shape
{
public:
virtual double area() = 0;
virtual double perimeter() = 0;
};
class Circle : public Shape
{
private:
double radius;
public:
Circle(double r)
{
radius=r;
}
double area()
{
return 3.142 * radius * radius;
}
double perimeter()
{
return 2 * 3.142 * radius;
}
};
int main()
{
double a,p;
Circle circle(5);
a = circle.area();
p = circle.perimeter();
cout<<"Area of the circle = "<<a<<endl;
cout<<"Perimeter of the circle = "<<p<<endl;
return 0;
}
Output
Area of the circle = 78.55 Perimeter of the circle = 31.42
Abstract classes can also contain non-pure virtual functions, which are functions that have a default implementation but can be overridden by derived classes if needed. see the example given below.
Example
#include <iostream>
using namespace std;
class Shape
{
public:
virtual double area() = 0;
virtual void draw()
{
cout<<"Drawing shape"<<endl;
}
};
class Circle : public Shape
{
private:
double radius;
public:
Circle(double r)
{
radius=r;
}
double area()
{
return 3.142 * radius * radius;
}
void draw()
{
cout<<"Drawing circle"<<endl;
}
};
int main()
{
double a;
Circle circle(5);
circle.draw();
return 0;
}
Output
Drawing circle
In the above program, the Circle class has overridden the draw() function of the base class Shape. When we call the draw() function over the Circle class object, it uses the overridden implementation.