What an abstract class is
An abstract class is a base class that you use to build other classes. You don’t create objects from it directly. In C++, a class becomes abstract when it has at least one pure virtual function, which is a virtual function declared with = 0 at the end.
The purpose is to define a shared interface: a set of functions that every derived class must provide. Code can then work with any derived object through a pointer or reference to the base type. Abstract classes are one of the main tools for polymorphism in c, because one base type can stand in for many derived types.
A complete example
The example models shapes. Shape says what every shape must be able to do. It can’t compute an area on its own, so it leaves that to the derived classes.
#include <iostream>
#include <memory>
#include <string>
#include <vector>
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0; // Pure virtual
virtual std::string name() const = 0; // Pure virtual
void describe() const {
std::cout << name() << " with area " << area() << "\n";
}
};
class Circle : public Shape {
public:
explicit Circle(double radius) : radius_(radius) {}
double area() const override { return 3.14159 * radius_ * radius_; }
std::string name() const override { return "Circle"; }
private:
double radius_;
};
class Rectangle : public Shape {
public:
Rectangle(double width, double height) : width_(width), height_(height) {}
double area() const override { return width_ * height_; }
std::string name() const override { return "Rectangle"; }
private:
double width_;
double height_;
};
int main() {
// Shape s; // Error: Shape is abstract
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(2.0));
shapes.push_back(std::make_unique<Rectangle>(3.0, 4.0));
for (const auto& shape : shapes) {
shape->describe();
}
}
Circle and Rectangle each provide area() and name(). The override keyword asks the compiler to confirm that each function really overrides a base class function. describe() is an ordinary function in Shape. It calls the pure virtual functions, so it works for any shape, and each call reaches the right version at run time.
The shapes vector holds std::unique_ptr<Shape> values. The virtual destructor in Shape makes sure each derived object is cleaned up correctly when the vector is destroyed. Running the program prints Circle with area 12.5664 and Rectangle with area 12.
Rules for abstract classes
- You can’t create an object of an abstract class. A line like
Shape s;won’t compile. - You can create pointers and references to an abstract class. They can refer to objects of any class derived from it.
- A derived class stays abstract until it overrides every pure virtual function it inherits.
- An abstract class can have data members, constructors and ordinary member functions. Derived classes call its constructor the same way they would for any base class. See c class constructor for the basics.
- An abstract class can’t be a parameter type or a return type when it’s passed or returned by value. Use a reference or a pointer instead.
class Square : public Shape {
// No area() or name(), so Square is still abstract
};
// Square sq; // Error: Square is abstract
void print_area(const Shape& shape) { // Reference: allowed
std::cout << shape.area() << "\n";
}
// void print_area(Shape shape); // Error: Shape is abstract
Pure virtual functions can have a body
A pure virtual function can still have a definition outside the class. Derived classes can call the base version by writing the base class name. This is less common, but it’s useful when the base class has default behavior that derived classes want to reuse.
class Base {
public:
virtual void run() = 0;
};
void Base::run() {
std::cout << "Base run\n";
}
class Derived : public Base {
public:
void run() override {
Base::run(); // Calls the base version explicitly
std::cout << "Derived run\n";
}
};
Virtual destructors
If you delete a derived object through a base pointer, the base class’s destructor must be virtual. Without it, the behavior is undefined, and the derived part may not be cleaned up. This is why the Shape example declares virtual ~Shape() = default;.
Common mistakes
Calling a pure virtual function from a constructor. While the base constructor runs, the derived part of the object doesn’t exist yet, so there is no final version of the function to call. Doing this is undefined behavior. Many runtimes stop the program with an error such as “pure virtual method called.”
class Base {
public:
Base() {
setup(); // Undefined behavior: setup() is pure virtual
}
virtual void setup() = 0;
};
Getting the signature slightly wrong. Shape::area() is declared const. If a derived class writes double area() without const, that’s a new function rather than an override, so the class stays abstract. Adding override makes the compiler report the mistake right away.
Abstract classes and interfaces
C++ has no interface keyword. Java and C# do, and they use it to list methods that a class must implement. In C++, programmers often use an abstract class with only pure virtual functions and no data members as an interface.
Code that depends on such an interface, rather than on one concrete class, is often easier to change and test. Accepting an abstract type as a parameter is a common starting point for dependency injection in c.
Access and abstract classes
Put the functions that other code should call in public. Put helpers that only derived classes need in protected. The rules for each section are covered in access modifiers in c.
When to use one
- Several classes share the same set of operations, but each one does them differently.
- Code should work through one type without caring which class it has.
- The base class has no useful meaning as an object of its own. A generic shape, for example, has no area until you know what kind of shape it is.
Key takeaways
An abstract class is a base class with at least one pure virtual function. You can’t create objects from it directly. Derived classes must implement the pure virtual functions, and a virtual destructor keeps deletion through base pointers safe. Used this way, abstract classes give you a clear interface that code can rely on.