What is Abstract Class in C++: Definition and Usage
abstract class in C++ is a class that cannot be instantiated directly and contains at least one pure virtual function. It serves as a blueprint for other classes to inherit and implement the pure virtual functions.How It Works
Think of an abstract class as a blueprint for a house. You cannot live in the blueprint itself, but it shows how the house should be built. In C++, an abstract class defines some functions without giving their full details, called pure virtual functions. These functions must be completed by any class that inherits from the abstract class.
This means you cannot create an object directly from an abstract class because it is incomplete. Instead, you create objects from classes that fill in the missing details. This helps organize code by forcing certain functions to be implemented in child classes, ensuring a consistent interface.
Example
This example shows an abstract class Shape with a pure virtual function area(). The classes Circle and Rectangle inherit from Shape and provide their own area() implementations.
#include <iostream> #define _USE_MATH_DEFINES #include <cmath> class Shape { public: virtual double area() const = 0; // pure virtual function virtual ~Shape() = default; // virtual destructor }; class Circle : public Shape { double radius; public: Circle(double r) : radius(r) {} double area() const override { return M_PI * radius * radius; } }; class Rectangle : public Shape { double width, height; public: Rectangle(double w, double h) : width(w), height(h) {} double area() const override { return width * height; } }; int main() { Circle c(5); Rectangle r(4, 6); std::cout << "Circle area: " << c.area() << "\n"; std::cout << "Rectangle area: " << r.area() << "\n"; // Shape s; // Error: cannot instantiate abstract class return 0; }
When to Use
Use abstract classes when you want to define a common interface for a group of related classes but leave some details to be implemented by each specific class. This is useful in large programs where different objects share behaviors but differ in implementation.
For example, in a graphics program, you might have an abstract Shape class with functions like draw() and area(). Different shapes like circles, rectangles, and triangles implement these functions differently. This design helps keep code organized and flexible.
Key Points
- An abstract class has at least one pure virtual function declared with
= 0. - You cannot create objects of an abstract class directly.
- Derived classes must implement all pure virtual functions to be instantiable.
- Abstract classes define interfaces and enforce consistent behavior across subclasses.