Skip to main content

Abstract class with example

Short answer

An abstract class is a base class with at least one pure virtual function (e.g., virtual float area() = 0;). It cannot be instantiated; derived classes must override all pure virtual functions. Example: Shape defines area() as pure virtual, Circle and Square override it with different formulas.

Explain abstract class with example.

An abstract class is a class that cannot be instantiated and is meant to be used only as a base class. A class becomes abstract when it has at least one pure virtual function, declared as virtual return_type f() = 0;.

Key points

  • No object of an abstract class can be created, but pointers and references to it can.
  • It defines a common interface; derived classes must override all pure virtual functions, otherwise they are abstract too.
  • It can contain data members, constructors and ordinary member functions.
  • It is used to achieve run-time polymorphism.

Example

#include <iostream>
using namespace std;

class Shape {                         // abstract class
public:
    virtual float area() = 0;         // pure virtual function
    void show() { cout << "Area = " << area() << endl; }
};

class Circle : public Shape {
    float r;
public:
    Circle(float x) : r(x) {}
    float area() { return 3.14159f * r * r; }
};

class Square : public Shape {
    float s;
public:
    Square(float x) : s(x) {}
    float area() { return s * s; }
};

int main() {
    // Shape s;              // error: cannot create object of abstract class
    Shape *p;
    Circle c(2);
    Square q(3);
    p = &c; p->show();
    p = &q; p->show();
    return 0;
}

Output

Area = 12.5664
Area = 9

Shape only states that every shape must have an area(), while each derived class supplies its own formula.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 7 questions →