Sobes.tech
Junior

What is an abstract class?

sobes.tech AI

Answer from AI

An abstract class is a class that cannot be instantiated directly. It contains one or more pure virtual functions (methods without implementation), marked with = 0. It is used as a base class to define a common interface for derived classes, which are required to provide implementations for these pure virtual functions.

Main properties:

  • You cannot create an object of an abstract class: AbstractClass obj; — error.
  • It can contain regular (non-virtual) methods and data fields.
  • It can contain virtual methods with implementations and pure virtual methods.
  • Pointers or references of the base type can refer to it: AbstractClass* ptr = new DerivedClass();
  • Derived classes that do not implement all pure virtual functions of the base class also become abstract.

Example of usage for defining a contract:

// Abstract base class Shape
class Shape {
public:
    // Pure virtual method - each inheritor must implement it
    virtual double area() const = 0;
    // Virtual method with implementation
    virtual void printDescription() const {
        // Default description
    }
    // Non-virtual method
    void commonOperation() {
        // Common actions
    }
    // Virtual destructor is important for proper memory cleanup when working through base class pointers/references.
    virtual ~Shape() {}
};

// Derived class implementing the abstract method
class Circle : public Shape {
private:
    double radius;
public:
    Circle(double r) : radius(r) {}
    // Implementation of pure virtual method area()
    double area() const override {
        return 3.14159 * radius * radius;
    }
    // Override virtual method
    void printDescription() const override {
        // Description for circle
    }
    // Destructor
    ~Circle() override {}
};

// Another derived class
class Rectangle : public Shape {
private:
    double width, height;
public:
    Rectangle(double w, double h) : width(w), height(h) {}
    // Implementation of pure virtual method area()
    double area() const override {
        return width * height;
    }
    // Destructor
    ~Rectangle() override {}
};

// Usage example
int main() {
    //Shape s; // Error: cannot create an object of an abstract class

    Shape* shapes[2]; // Pointers to base class
    shapes[0] = new Circle(5.0);
    shapes[1] = new Rectangle(4.0, 6.0);

    for(int i = 0; i < 2; ++i) {
        // Polymorphic call of area()
        double a = shapes[i]->area();
        // Polymorphic call of printDescription()
        shapes[i]->printDescription();
        shapes[i]->commonOperation(); // Non-virtual method call
    }

    // Proper memory cleanup through base class pointers
    delete shapes[0];
    delete shapes[1];

    return 0;
}