OOP

Abstract Classes and Interfaces

Abstract classes and interfaces are fundamental concepts in C++ for achieving abstraction and promoting code reusability. While C++ doesn’t have a built-in interface concept like some other languages, abstract classes are often used to simulate interfaces. Here’s a breakdown of each:

Abstract Classes:

Applications of Abstract Classes:

Interfaces (Simulated using Abstract Classes):

Applications of Interfaces (Simulated):

Key Differences:

Choosing Between Abstract Classes and Interfaces:

Abstract Class Example: Shape with Area Calculation

#include <iostream>

using namespace std;

class Shape {
public:
  // Pure virtual function - must be overridden by derived classes
  virtual double getArea() const = 0;
};

class Rectangle : public Shape {
private:
  double width;
  double height;

public:
  Rectangle(double w, double h) : width(w), height(h) {}

  double getArea() const override {
    return width * height;
  }
};

class Circle : public Shape {
private:
  double radius;

public:
  Circle(double r) : radius(r) {}

  double getArea() const override {
    return 3.14159 * radius * radius;
  }
};

int main() {
  // You cannot create an object of the abstract class Shape
  // Shape shape; // This will cause an error

  Rectangle rectangle(5.0, 3.0);
  Circle circle(4.0);

  cout << "Rectangle area: " << rectangle.getArea() << endl;
  cout << "Circle area: " << circle.getArea() << endl;

  return 0;
}

Explanation: