Abstract Classes and interafaces - EduardoMSU/OOP-2143 GitHub Wiki

Abstract Classes and Interfaces

Abstract Classes

An abstract class is a class that cannot be instantiated on its own and must be subclassed by other classes. It can contain both abstract methods (methods that have no implementation) and concrete methods (methods with implementation).

Key Points:

  • Abstract classes allow both abstract methods (which must be implemented by subclasses) and concrete methods (with implementation).
  • An abstract class can have instance variables.
  • A class can inherit from only one abstract class (single inheritance).

Example in C++:

#include <iostream>

class Shape {
public:
    // Abstract method
    virtual void draw() = 0;

    // Concrete method
    void description() {
        std::cout << "I am a shape!" << std::endl;
    }

    virtual ~Shape() {} // Virtual destructor
};

class Circle : public Shape {
public:
    void draw() override {
        std::cout << "Drawing a circle!" << std::endl;
    }
};

int main() {
    // Shape shape; // Error: cannot instantiate an abstract class
    Circle circle;
    circle.draw(); // Calls Circle's draw method
    circle.description(); // Calls the concrete description method

    return 0;
}
⚠️ **GitHub.com Fallback** ⚠️