What is Abstract Class?

In C++, an abstract class is a class that cannot be instantiated directly, meaning you cannot create objects of that class. It is designed to serve as a base class for other classes and defines a common interface that its derived classes must implement.

To create an abstract class in C++, you need to have at least one pure virtual function. A pure virtual function is a virtual function that is declared in the base class but does not have an implementation. The syntax for declaring a pure virtual function is as follows:

virtual returnType functionName(parameters) = 0;

Here’s an example of an abstract class called Shape, which has a pure virtual function area():

#include <iostream>

class Shape {
public:
    virtual double area() = 0;  // Pure virtual function

    void printArea() {
        std::cout << "Area: " << area() << std::endl;
    }
};

class Rectangle : public Shape {
private:
    double length;
    double width;

public:
    Rectangle(double l, double w) : length(l), width(w) {}

    double area() {
        return length * width;
    }
};

class Circle : public Shape {
private:
    double radius;

public:
    Circle(double r) : radius(r) {}

    double area() {
        return 3.14159 * radius * radius;
    }
};

int main() {
    // Shape shape;  // Error: Cannot instantiate an abstract class

    Rectangle rectangle(5, 3);
    Circle circle(2.5);

    rectangle.printArea();
    circle.printArea();

    return 0;
}

In the example above, the Shape class is an abstract class because it contains the pure virtual function area(). It cannot be instantiated directly, but it provides a common interface for its derived classes (Rectangle and Circle). The derived classes inherit the area() function and provide their own implementations.

Note that attempting to create an object of the Shape class directly will result in a compilation error. However, you can create objects of the derived classes and invoke the printArea() function, which internally calls the area() function specific to each derived class.

Leave a Reply

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