C++ Abstraction
In this page:
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?
#include <iostream>
class Car {
public:
void start() {
std::cout << "Car started" << std::endl;
}
};
int main() {
Car car;
car.start();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: