C++ ยท Chapter 39 of 49

C++ Abstraction

Abstraction means exposing only essential features of an object while hiding complex implementation details, letting users interact with a simple interface. In C++, abstract classes and pure virtual functions are the primary tool for defining such interfaces.

For example, a `Shape` interface might declare `area()` without saying how each shape computes it โ€” callers only need to know that every Shape can report its area.

Abstract classes as interfaces

An abstract class with only pure virtual functions acts like an 'interface' in other languages, defining a contract that derived classes must fulfil.

Abstraction vs encapsulation

Abstraction hides complexity at the design level (what an object does), while encapsulation hides data at the implementation level (how it's stored) โ€” they work together.

Example 1 (cpp)
class Shape {
public:
    virtual double area() = 0;
};
class Square : public Shape {
public:
    double side;
    Square(double s) : side(s) {}
    double area() override { return side * side; }
};
int main() {
    Shape* s = new Square(4);
    std::cout << s->area();
    delete s;
}
Output
16

Callers only need Shape's area() interface, not Square's internal formula.

Key points

  • Abstraction hides implementation, exposing only essential behaviour.
  • Abstract classes with pure virtual functions act as interfaces.
  • Callers depend on the interface, not concrete implementation details.
  • Abstraction and encapsulation complement each other.
๐Ÿ’ก Note: Designing to interfaces (abstract classes) makes it easy to swap implementations without changing calling code.

๐Ÿ“ Quick Quiz

1. Abstraction is mainly about:

2. Which C++ feature is commonly used to define an interface?

3. Abstraction and encapsulation are: