C++ Lesson 21 โ€“ Abstraction | Dataplexa
Object-Oriented Programming ยท Lesson 21

Abstraction

You drive a car without knowing how the engine burns fuel. You press a button on a coffee machine without knowing how the water is heated. You are using abstraction โ€” the art of hiding the details and showing only what matters. In this lesson you will learn how C++ builds that idea into classes: abstract classes, pure virtual functions, and interfaces.

What Is Abstraction?

Abstraction means showing the what and hiding the how. A car shows you a steering wheel, pedals, and a gear stick. It hides the engine, the fuel injection, and the gearbox. You do not need to know how the engine works to drive to the shops โ€” and the car maker can change the engine later without teaching you to drive all over again.

You have already been using abstraction in every lesson so far. std::string hides how text is stored in memory. std::cin and std::cout hide how the keyboard and screen really work. std::vector (Lesson 38) hides how a growing list is managed. Each of them gives you a small, simple set of tools โ€” and keeps the machinery out of sight.

Abstraction is one of the four pillars of OOP from Lesson 13. It is easy to confuse with encapsulation, so here is the difference: abstraction hides the HOW โ€” the implementation โ€” while encapsulation hides the DATA โ€” the members themselves. Encapsulation is the subject of the next lesson, Lesson 22.

Code story: Here is a small program that shows abstraction at work. We build a Car class that keeps its engine private, then in main we simply drive the car and stop it. Watch for what main never touches: the engine.

#include <iostream>
#include <string>

class Car {
private:
    std::string engine;
public:
    Car() : engine("petrol") {}
    void drive() {
        std::cout << "The car is moving.\n";
    }
    void stop() {
        std::cout << "The car has stopped.\n";
    }
};

int main() {
    Car myCar;
    myCar.drive();
    myCar.stop();
    return 0;
}
The car is moving.
The car has stopped.

The driver is the lesson: in main, myCar.drive() and myCar.stop() are all you need. The engine member is private, and nothing in main ever touches it โ€” the how stays hidden inside the class.

Abstract Classes โ€” A Class You Cannot Build

Sometimes a class exists only to describe an idea, not to be built itself. A Shape is a good example: every shape has an area, but there is no such thing as a plain Shape โ€” there are only circles, rectangles, and triangles. In C++ you express that idea with an abstract class: a class with at least one pure virtual function.

A pure virtual function is written with = 0 instead of a body. It says: every child of this class MUST provide its own version of this function. The base class does not know how to calculate an area โ€” each shape knows how to calculate its own.

Code story: Now let us see an abstract class in action. Shape declares that every shape must have an area, but it does not calculate one. Circle and Rectangle each work out their own area, and main prints both. Watch for the = 0 โ€” it is what makes Shape abstract.

#include <iostream>

class Shape {
public:
    virtual double area() = 0;
    virtual ~Shape() = default;
};

class Circle : public Shape {
private:
    double radius;
public:
    Circle(double r) : radius(r) {}
    double area() override {
        return 3.14159 * radius * radius;
    }
};

class Rectangle : public Shape {
private:
    double width, height;
public:
    Rectangle(double w, double h) : width(w), height(h) {}
    double area() override {
        return width * height;
    }
};

int main() {
    Circle circle(5);
    Rectangle rectangle(6, 4);
    std::cout << "Circle area: " << circle.area() << "\n";
    std::cout << "Rectangle area: " << rectangle.area() << "\n";
    return 0;
}
Circle area: 78.5398
Rectangle area: 24

Try writing Shape shape; in main and the compiler will refuse: it cannot create an object of an abstract class. But you can point to it โ€” Shape* s = new Circle(5); works, and s->area() calls the Circle version because area() is virtual (Lesson 18). That is the whole point: the abstract class defines the contract, and the children fulfil it.

Rule of thumb: = 0 means 'no body here โ€” children must provide it'. One pure virtual function is enough to make the whole class abstract.

Pure Virtual Functions โ€” The Rules

Pure virtual functions have a few rules worth knowing before you use them:

First, a class with at least one pure virtual function is abstract โ€” it cannot be instantiated. Second, a child class that does not implement every pure virtual function stays abstract too, so it cannot be created either. Third, an abstract class can still have a constructor, a destructor, and ordinary (non-virtual) functions with bodies โ€” only the pure virtual functions are missing a body. Fourth, a pure virtual function can actually have a body written separately (a rare trick for a default behaviour) โ€” but the class stays abstract all the same.

Code story: This program is a promise in code. Vehicle says every vehicle must have a start() function, but it does not say how to start. Car turns a key and Bike kick-starts, and main just calls start() on each. Watch for override โ€” it proves each child really keeps the promise.

#include <iostream>
#include <string>

class Vehicle {
public:
    virtual void start() = 0;
    virtual ~Vehicle() = default;
};

class Car : public Vehicle {
public:
    void start() override {
        std::cout << "Car: turning the key.\n";
    }
};

class Bike : public Vehicle {
public:
    void start() override {
        std::cout << "Bike: kick-starting.\n";
    }
};

int main() {
    Car car;
    Bike bike;
    car.start();
    bike.start();
    return 0;
}
Car: turning the key.
Bike: kick-starting.

Notice that Vehicle says nothing about keys or kick-starts โ€” it only says 'every vehicle must have a start()'. The Car and the Bike each fill in their own version. That is abstraction working as a contract: the base class fixes the what, and each derived class supplies the how.

Interfaces โ€” A Class That Is Only a Contract

An interface is an abstract class taken to its limit: it contains only pure virtual functions (and usually no data members at all). It has no behaviour of its own โ€” it is just a promise that any class claiming the interface must keep.

Code story: Here is an interface doing its job. Drawable contains only one promise: every drawable thing must have a draw() function. Circle and Square each draw themselves, and main just asks each one to draw. Watch for what Drawable does not have โ€” no data, no bodies, only the promise.

#include <iostream>

class Drawable {
public:
    virtual void draw() = 0;
    virtual ~Drawable() = default;
};

class Circle : public Drawable {
public:
    void draw() override {
        std::cout << "Drawing a circle.\n";
    }
};

class Square : public Drawable {
public:
    void draw() override {
        std::cout << "Drawing a square.\n";
    }
};

int main() {
    Circle circle;
    Square square;
    circle.draw();
    square.draw();
    return 0;
}
Drawing a circle.
Drawing a square.

C++ has no keyword for an interface โ€” it is just a naming convention for an abstract class that holds only pure virtual functions. Other languages spell it differently, but the idea is the same everywhere: a shared contract that unrelated classes can all follow.

An interface is a promise: any class that claims to be Drawable MUST have a draw() function. Code that takes a Drawable* never needs to know whether it is looking at a circle or a square.

FeatureAbstract classInterface
Data membersCan have themUsually none
Methods with a bodyCan have themNone โ€” every method is pure virtual
Use it whenSome behaviour is shared by the childrenOnly a contract is shared
ExampleShape with area() and a colour memberDrawable with draw() only

Abstraction in the Real World โ€” What Already Hides Details

The best abstractions are the ones you never notice. When you write std::cout << "Hello"; you never think about pushing pixels onto a screen. When you open a file with std::ofstream (Lesson 31) you never think about disk sectors. A good function does the same thing on a smaller scale: it hides its how behind a clear name.

Code story: Here is abstraction in a single function. logMessage() takes a message and writes it to a file, and main just calls it twice and prints Done. Watch for what main never sees: opening the file, appending, or the newline. If the file becomes a database tomorrow, main will not change.

#include <fstream>
#include <iostream>
#include <string>

void logMessage(const std::string& message) {
    std::ofstream log("app.log", std::ios::app);
    log << message << '\n';
}

int main() {
    logMessage("User logged in.");
    logMessage("Order placed.");
    std::cout << "Done.\n";
    return 0;
}
Done.

The caller of logMessage() only knows one thing: pass a message, and it gets written to a log. Opening the file, appending instead of overwriting, writing the newline โ€” all of that is hidden inside the function. If you later decide to write the log to a database instead, main() does not change at all. That is abstraction paying for itself: the fewer details a caller needs, the fewer places break when the details change.

Common Mistakes with Abstraction

MistakeWhat happensFix
Creating an object of an abstract classThe compiler refuses: 'cannot declare variable to be of abstract type'Create an object of a derived class, or use a pointer or reference to the abstract type
Forgetting to implement one pure virtual function in a childThe child stays abstract, so it cannot be created eitherImplement every pure virtual function, or declare the child abstract on purpose
Forgetting a virtual destructor in the base classdelete through a base pointer destroys only the base part โ€” a leakGive the base class a virtual destructor (usually = default)
Mixing up abstraction and encapsulationYou hide the wrong thing โ€” or hide nothing at allAbstraction hides the HOW (implementation); encapsulation hides the DATA โ€” Lesson 22
Making everything an interfaceSmall classes grow extra layers that nobody needsUse an interface only when several unrelated classes share one contract

Practice โ€” Hiding the Details

Try these before moving on. Write each program, compile it, and check the output.

  1. Write an abstract class Shape with a pure virtual double area() and a pure virtual void draw(). Then write Circle and Rectangle classes that implement both, and print the area of each.
  2. Write a Drawable interface (only pure virtual functions) with draw(). Make Triangle and Line implement it, and call draw() on each through a Drawable pointer.
  3. Add a virtual destructor to your Shape class, then delete a Shape* that points to a Circle. Print a message from each destructor so you can see which destructors run.
  4. Try to create an object of your abstract Shape class. Read the compiler error, then fix the code by creating a Circle instead.

What is abstraction?


What makes a class abstract in C++?


Can you create an object of an abstract class?


Fill in the blanks โ€” type the missing word into the box.

A virtual function written with = 0 is called a virtual function.


A class that has at least one pure virtual function is called an class.


A class that contains only pure virtual functions is often called an .


Up Next

Encapsulation

Next, the other half of hiding: keeping the data safe inside the class.