Lesson 24 of 45
C++Lesson 24: Abstract Classes and Interfaces
9 min
Course progress53%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 24 of 45
C++9 min
Keep these ideas in mind as you work through the lesson.
An abstract class contains at least one pure‑virtual function, making it impossible to instantiate directly. Abstract classes are often used to define interfaces – contracts that derived classes must fulfil.
Printable interfaceclass Printable {
public:
virtual void print(std::ostream& os) const = 0;
virtual ~Printable() = default;
};
class Person : public Printable {
std::string name;
int age;
public:
Person(std::string n, int a) : name(std::move(n)), age(a) {}
void print(std::ostream& os) const override {
os << \"Person: \" << name << ", age " << age;
}
};
int main() {
Person p(\"Bob\", 30);
p.print(std::cout);
std::cout << '\
';
return 0;
}
If you need multiple unrelated contracts, you can inherit from several abstract classes (multiple inheritance). The C++20 concepts feature can also express interface‑like requirements without inheritance.
Tip: Keep interfaces minimal – only pure virtual functions and a virtual destructor.
<Alert type="info">Abstract classes can contain non‑virtual helper functions and data members, offering a blend of concrete and abstract behaviour.