← Back to C++ Course | Chapter 10: Polymorphism & Abstraction | Lesson 8 of 11

C++ Abstraction

What is Abstraction?

Abstraction is the process of hiding an object's complex internal implementation while exposing only the essential features a user actually needs to interact with it. This lets programmers work with high-level concepts without being distracted by low-level mechanics they don't need to know.

Example: What is Abstraction?

cpp
#include <iostream>

class Car {
public:
	void start() {
		std::cout << "Car started" << std::endl;
	}
};

int main() {
	Car car;
	car.start();
	return 0;
}

Abstract Classes

An abstract class is a class specifically designed to serve as a blueprint for other classes: it contains at least one pure virtual function and, as a direct consequence, can never be instantiated on its own.

Example: Abstract Classes

cpp
#include <iostream>

class Shape {
public:
	virtual void draw() = 0;
};

class Circle : public Shape {
public:
	void draw() override { std::cout << "Circle" << std::endl; }
};

int main() {
	Circle c;
	c.draw();
	return 0;
}

Pure Virtual Functions

A pure virtual function is declared in a base class with no implementation of its own — its body is replaced entirely by setting the declaration equal to 0 — leaving that specific piece of behavior entirely up to whatever subclass eventually implements it.

Example: Pure Virtual Functions

cpp
#include <iostream>

class Shape {
public:
	virtual void draw() = 0;
};

class Square : public Shape {
public:
	void draw() override { std::cout << "Square" << std::endl; }
};

int main() {
	Square s;
	s.draw();
	return 0;
}

Implementation of Abstraction

To actually put abstraction into practice, every concrete class that derives from an abstract parent must override and provide a real implementation for each pure virtual function it inherited, or else it remains abstract itself and can't be instantiated either.

Example: Implementation of Abstraction

cpp
#include <iostream>

class Shape {
public:
	virtual void draw() = 0;
};

class Triangle : public Shape {
public:
	void draw() override { std::cout << "Triangle" << std::endl; }
};

int main() {
	Triangle t;
	t.draw();
	return 0;
}

Advantages of Abstraction

Abstraction pays off by reducing code duplication and cleanly separating a system's design from its implementation details — a benefit that keeps large, evolving codebases scalable rather than turning into a tangle of copy-pasted logic.

Example: Advantages of Abstraction

cpp
#include <iostream>

class PaymentMethod {
public:
	virtual void pay() = 0;
};

class Cash : public PaymentMethod {
public:
	void pay() override { std::cout << "Paid with cash" << std::endl; }
};

int main() {
	Cash cash;
	cash.pay();
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.