Learn C++
#include "oopadvanced/abstract_classes.hpp"

Abstract Classes & Pure Virtual Functions in C++

//concept

Appending = 0 to a virtual function makes it pure — no implementation required in the base, and the class becomes abstract: it can never be instantiated, only inherited from. Abstract classes define interfaces (what implementers must provide) while optionally sharing common code and state alongside.

A class with any unimplemented pure virtual stays abstract down the hierarchy until some descendant implements them all. Destructors can be pure too (still requiring a body!), and interfaces in C++ are simply abstract classes with only pure virtuals.

//how it works
1

= 0 means must override

virtual void draw() = 0; declares an obligation with no default — derived classes implement it or stay abstract themselves.

2

Abstract means uninstantiable

Shape s; fails to compile when Shape has pure virtuals — only concrete descendants (all pure virtuals implemented) can be created.

3

Interfaces are pure-abstract classes

A class of only public pure virtuals plus a virtual destructor is C++'s interface idiom — no separate interface keyword needed.

4

Pure destructors still need bodies

virtual ~Base() = 0; is legal but must be defined ({}), because derived destructors always invoke it.

//example
#include <iostream>
 
class Shape {
public:
virtual double area() = 0;
virtual ~Shape() = default;
};
 
class Square : public Shape {
double side;
public:
explicit Square(double s) : side(s) {}
double area() override { return side * side; }
};
 
int main() {
Shape* s = new Square(4.0);
std::cout << s->area() << std::endl;
delete s;
return 0;
}
Output
16
1Shape declares the area contract but provides no implementation — it cannot be instantiated itself.
2Square implements area, becoming concrete and constructible.
3Through the Shape* interface, Square's 4x4 = 16 computes and prints.
//use cases
Plugin APIs: abstract factory and handler interfaces third parties implement
Test seams: depending on abstract services that mocks can stand in for
Forcing every shape/renderer/codec to implement its core operation
Sharing common state plus a partial default while mandating key behaviors

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.