Skip to content

Module 5 · Classes and Objects — topic 5 of 5

Abstraction

Abstraction shows what an object does and hides how it does it. Learn abstract interfaces with pure virtual functions, header/source separation, and designing to an interface.

Beginner 13 min read·Lesson 21 of 40 in C++ Programming

Learning objectives

  • Design a class interface that hides implementation
  • Declare abstract classes with pure virtual functions
  • Write code that depends on an interface, not a concrete class

Definition

Abstraction is the practice of exposing only the essential behaviour of a component through a simplified interface while hiding implementation details; in C++ it is expressed with clean class interfaces and abstract base classes containing pure virtual functions.

Introduction

You drive a car through a steering wheel and pedals without knowing how the engine works. Abstraction gives software the same property: callers use storage.save(record) without caring whether it writes to a file, a database or memory.

Why it matters

Abstraction lets you swap implementations — for testing or new requirements — without touching calling code.

Abstract classes are the C++ way to define interfaces, used throughout frameworks and the projects in this course.

Detailed explanation

Encapsulation hides data; abstraction hides complexity. They work together: a good class has a small, meaningful public interface.

A pure virtual function is declared virtual void draw() const = 0;. A class with at least one is abstract and cannot be instantiated.

Derived classes implement the pure virtual functions; code holds a reference or pointer to the abstract base and calls through it (runtime polymorphism, covered in the next module).

An interface class should have a virtual destructor so objects deleted through a base pointer are destroyed correctly.

Syntax

C++
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0; // pure virtual
virtual std::string name() const = 0;
};
class Circle : public Shape {
public:
explicit Circle(double r) : r_(r) {}
double area() const override { return 3.14159 * r_ * r_; }
std::string name() const override { return "circle"; }
private:
double r_;
};
  • = 0 marks a pure virtual function.
  • override asks the compiler to check the signature.
  • You can't create a Shape directly.

Code examples

Using an abstract interface

C++
#include <iostream>
#include <string>
class Greeter {
public:
virtual ~Greeter() = default;
virtual std::string greet(const std::string& name) const = 0;
};
class English : public Greeter {
public:
std::string greet(const std::string& n) const override { return "Hello, " + n; }
};
class Hindi : public Greeter {
public:
std::string greet(const std::string& n) const override { return "Namaste, " + n; }
};
void welcome(const Greeter& g) { std::cout << g.greet("Asha") << '\n'; }
int main() {
welcome(English{});
welcome(Hindi{});
return 0;
}
Output
Hello, Asha
Namaste, Asha

Abstract classes cannot be instantiated

C++
class Shape {
public:
virtual double area() const = 0;
};
int main() {
Shape s; // error: cannot declare variable 's' to be of abstract type 'Shape'
}

More examples

Swapping storage implementations

C++
#include <iostream>
#include <map>
#include <memory>
#include <string>
class Storage {
public:
virtual ~Storage() = default;
virtual void put(const std::string& key, int value) = 0;
virtual int get(const std::string& key) const = 0;
};
class MemoryStorage : public Storage {
public:
void put(const std::string& k, int v) override { data_[k] = v; }
int get(const std::string& k) const override {
auto it = data_.find(k);
return it == data_.end() ? 0 : it->second;
}
private:
std::map<std::string, int> data_;
};
class LoggingStorage : public Storage {
public:
explicit LoggingStorage(std::unique_ptr<Storage> inner) : inner_(std::move(inner)) {}
void put(const std::string& k, int v) override { std::cout << "put " << k << '\n'; inner_->put(k, v); }
int get(const std::string& k) const override { std::cout << "get " << k << '\n'; return inner_->get(k); }
private:
std::unique_ptr<Storage> inner_;
};
int score_total(Storage& s) { // depends only on the interface
s.put("maths", 88);
s.put("physics", 76);
return s.get("maths") + s.get("physics");
}
int main() {
MemoryStorage plain;
std::cout << score_total(plain) << '\n';
LoggingStorage logged(std::make_unique<MemoryStorage>());
std::cout << score_total(logged) << '\n';
return 0;
}
Output
164
put maths
put physics
get maths
get physics
164

Step-by-step explanation

  • Storage declares what a store can do, not how.
  • MemoryStorage implements it with a map; LoggingStorage wraps any other storage (the decorator pattern).
  • score_total works with both because it only knows the interface.
  • Adding a file-backed storage later would not change score_total.

Expected output

Running “Swapping storage implementations” prints exactly:

TextOutput
164
put maths
put physics
get maths
get physics
164

Practical applications

  • Database drivers implement a common interface so applications can switch databases.
  • Unit tests replace real services with fake implementations of the same interface.
  • GUI frameworks define abstract widgets with draw and handle-event functions.

Best practices

  • Program to interfaces, not implementations.
  • Keep interfaces small and cohesive.
  • Give polymorphic base classes virtual destructors.

Common mistakes

Missing virtual destructor in a base class

Avoid

class Base { public: virtual void f() = 0; };
std::unique_ptr<Base> p = std::make_unique<Derived>();

Prefer

class Base { public: virtual ~Base() = default; virtual void f() = 0; };

Deleting a derived object through a base pointer without a virtual destructor is undefined behaviour.

Leaking implementation details in the interface

Avoid

class Storage { public: std::map<std::string,int>& raw(); };

Prefer

class Storage { public: virtual int get(const std::string&) const = 0; };

Exposing the map ties every caller to one implementation.

Important notes

  • C++ has no interface keyword; an abstract class with only pure virtual functions plays that role.
  • C++20 concepts provide compile-time abstraction for templates without virtual functions.

Key takeaways

  • Abstraction exposes what, hides how.
  • Pure virtual functions make a class abstract.
  • Depend on abstract interfaces to swap implementations easily.

Try it yourself

  1. 1
    Define an abstract PaymentMethod with pay(amount) and implement UpiPayment and CardPayment.
  2. 2
    Write a FileStorage implementing Storage with a text file and use it with score_total.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

3 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat makes a C++ class abstract?
  • BeginnerGiven `class Shape { public: virtual double area() const = 0; };`, what happens with `Shape s;`?
  • ModerateWhy should code depend on an abstract `Storage&` rather than on `FileStorage&`?
Practise this topic