Introduction & Syntax
Abstract Classes and Interfaces · Study material
An abstract class in C++ is a class with at least one pure virtual function – a function declared with = 0 that derived classes must implement. You cannot create objects of an abstract class, but you can use pointers and references to it, and that is exactly how C++ programs define interfaces: contracts that many different classes promise to fulfil. Plug-in systems, device drivers, payment gateways, unit-test mocks and GUI toolkits are all built this way. Interviewers love the details – "can an abstract class have a constructor?", "what is a pure virtual destructor?", "what is the difference between an abstract class and an interface?". This page answers them all with runnable programs, then tests you with 60 practice questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – all verified on a real C++ compiler.
On this page
- Pure virtual functions and the rules of abstract classes
- Interface classes and implementing several interfaces
- Pure virtual destructors and pure virtual functions with a body
- Partially abstract classes and std::is_abstract
- Abstract class vs interface vs C++20 concept, and good interface design
Pure virtual functions and abstract classes
Syntax: virtual return-type name(params) = 0;. A class that declares or inherits a pure virtual function without overriding it is abstract. The rules:
- You cannot create an object of an abstract class – not as a variable, a by-value parameter, a return value or an array element.
- You can declare pointers and references to it, and they can refer to objects of concrete derived classes.
- An abstract class can have data members, ordinary member functions and constructors (used by derived classes).
- A derived class becomes concrete only when it overrides every pure virtual function.
#include <iostream>
#include <memory>
#include <string>
#include <vector>
// Abstract class: shared data and code PLUS functions every subclass must provide
class Employee {
protected:
std::string name_;
public:
explicit Employee(std::string n) : name_(std::move(n)) {} // abstract classes can have constructors
virtual double salary() const = 0; // pure virtual: no sensible default
virtual std::string role() const = 0;
void print() const { std::cout << name_ << " (" << role() << "): " << salary() << '\n'; } // shared code
virtual ~Employee() = default;
};
class Manager : public Employee {
public:
using Employee::Employee;
double salary() const override { return 90000; }
std::string role() const override { return "manager"; }
};
class Intern : public Employee {
int months_;
public:
Intern(std::string n, int m) : Employee(std::move(n)), months_(m) {}
double salary() const override { return 15000 + 1000.0 * months_; }
std::string role() const override { return "intern"; }
};
int main() {
// Employee e("x"); error: cannot create an abstract class
std::vector<std::unique_ptr<Employee>> staff; // pointers to the abstract type are fine
staff.push_back(std::make_unique<Manager>("Asha"));
staff.push_back(std::make_unique<Intern>("Ravi", 3));
for (const auto& e : staff) e->print();
return 0;
}
Asha (manager): 90000 Ravi (intern): 18000
Interfaces in C++
C++ has no interface keyword. By convention an interface is an abstract class with only pure virtual functions, a virtual destructor and no data. A class can implement many interfaces through multiple inheritance – safe and simple, because the interfaces carry no state.
#include <iostream>
#include <string>
// Interfaces: only pure virtual functions and a virtual destructor – no data
class Drawable {
public:
virtual void draw() const = 0;
virtual ~Drawable() = default;
};
class Clickable {
public:
virtual void on_click() = 0;
virtual ~Clickable() = default;
};
// One class can implement several interfaces
class Button : public Drawable, public Clickable {
std::string label_;
int clicks_ = 0;
public:
explicit Button(std::string l) : label_(std::move(l)) {}
void draw() const override { std::cout << "[ " << label_ << " ] clicks=" << clicks_ << '\n'; }
void on_click() override { ++clicks_; }
};
void render(const Drawable& d) { d.draw(); }
void simulate(Clickable& c, int n) { while (n--) c.on_click(); }
int main() {
Button ok("OK");
simulate(ok, 3); // sees only the Clickable part
render(ok); // sees only the Drawable part
return 0;
}
[ OK ] clicks=3
Pure virtual destructors
A destructor can be pure virtual – useful to make a class abstract when no other function is a natural candidate. Unlike other pure virtual functions it must be defined, because every derived class's destructor calls it; without a definition the program fails to link.
#include <iostream>
// A class with no other natural pure virtual function can be made abstract with a pure virtual destructor
struct Event {
virtual ~Event() = 0; // pure virtual destructor…
};
Event::~Event() { std::cout << "~Event "; } // …must still be DEFINED: derived destructors call it
struct KeyPress : Event {
char key;
explicit KeyPress(char k) : key(k) {}
~KeyPress() override { std::cout << "~KeyPress(" << key << ") "; }
};
int main() {
Event* e = new KeyPress('q');
delete e;
std::cout << '\n';
return 0;
}
~KeyPress(q) ~Event
Pure virtual functions with a body
A pure virtual function may also have a definition (written outside the class). The class stays abstract and every derived class must still override the function – but an override can call the shared default explicitly with Base::f(). This forces each subclass to make a conscious choice.
#include <iostream>
#include <string>
struct Notifier {
// Pure virtual WITH a definition: every subclass must decide, but can reuse the default
virtual std::string format(const std::string& msg) const = 0;
virtual ~Notifier() = default;
};
std::string Notifier::format(const std::string& msg) const { return "[notice] " + msg; }
struct Email : Notifier {
std::string format(const std::string& msg) const override { return Notifier::format(msg); } // opt in to default
};
struct Sms : Notifier {
std::string format(const std::string& msg) const override { return msg.substr(0, 11); } // custom
};
int main() {
Email e;
Sms s;
std::cout << e.format("Fees due on 5th") << '\n' << s.format("Fees due on 5th") << '\n';
return 0;
}
[notice] Fees due on 5th Fees due on
Partially abstract classes
An intermediate class may implement some pure virtual functions and leave others; it is still abstract. The type trait std::is_abstract_v<T> tells you at compile time.
#include <iostream>
#include <type_traits>
struct Shape { // abstract: two pure virtual functions
virtual double area() const = 0;
virtual double perimeter() const = 0;
virtual ~Shape() = default;
};
struct Polygon : Shape { // still abstract: implements only perimeter()
double side;
int n;
Polygon(double s, int k) : side(s), n(k) {}
double perimeter() const override { return side * n; }
};
struct Square : Polygon { // concrete: everything implemented
explicit Square(double s) : Polygon(s, 4) {}
double area() const override { return side * side; }
};
int main() {
std::cout << std::boolalpha
<< std::is_abstract_v<Shape> << ' '
<< std::is_abstract_v<Polygon> << ' '
<< std::is_abstract_v<Square> << '\n';
Square sq(3);
const Shape& s = sq;
std::cout << s.area() << ' ' << s.perimeter() << '\n';
return 0;
}
true true false 9 12
Abstract class vs interface vs concept
| Abstract class | Interface (pure abstract class) | C++20 concept | |
|---|---|---|---|
| Contains | pure virtual + normal functions, data, constructors | only pure virtual functions and a virtual destructor | requirements on a type |
| Purpose | share code and state, force some overrides | pure contract, no implementation | constrain templates |
| Inheritance needed | yes | yes (multiple is fine) | no – any type that fits |
| Dispatch | run time | run time | compile time |
#include <concepts>
#include <iostream>
#include <string>
// Run-time interface
struct Speaker {
virtual std::string speak() const = 0;
virtual ~Speaker() = default;
};
struct Dog : Speaker { std::string speak() const override { return "Woof"; } };
void talk(const Speaker& s) { std::cout << s.speak() << ' '; }
// Compile-time interface: any type with speak() – no base class needed
template <typename T>
concept CanSpeak = requires(const T& t) { { t.speak() } -> std::convertible_to<std::string>; };
struct Robot { std::string speak() const { return "Beep"; } }; // unrelated to Speaker
template <CanSpeak T>
void talk_static(const T& t) { std::cout << t.speak() << ' '; }
int main() {
talk(Dog{});
talk_static(Dog{});
talk_static(Robot{});
std::cout << '\n' << CanSpeak<int> << CanSpeak<Robot> << '\n';
return 0;
}
Woof Woof Beep 01
Common mistakes
- Trying to create an object of an abstract class, or passing/returning it by value.
- Forgetting one pure virtual function – the derived class silently stays abstract until you try to create it.
- Not defining a pure virtual destructor – a linker error.
- No virtual destructor in an interface – deleting through it is undefined behaviour.
- Calling a pure virtual function from a constructor or destructor – undefined behaviour (often "pure virtual function called" crash).
- Fat interfaces that force classes to implement functions they cannot support.
Key points to remember
= 0makes a virtual function pure; one pure function makes the class abstract.- No objects of abstract classes; pointers and references are fine.
- Abstract classes may have constructors, data and normal functions.
- Interface = only pure virtual functions + virtual destructor.
- Pure virtual destructors must be defined.
- Concepts give compile-time interfaces without inheritance.
Frequently asked questions
Can an abstract class have a constructor?
Yes. It cannot be called to create a standalone object, but derived constructors call it to initialise the base part. It is often made protected.
Can we create a pointer to an abstract class?
Yes – that is how abstract classes are used: Shape* p = new Circle; or const Shape& s = circle;.
Is a class with a pure virtual function that has a body still abstract?
Yes. Abstractness depends on the = 0, not on whether a definition exists.
Where can I learn more?
Read C++ Inheritance and Polymorphism and Object-Oriented Programming in C++, then practise with the exercises below.