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.
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;
}16Callers 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.
