Lesson 17 of 45 · C++
Lesson 24: Abstract Classes and Interfaces
Duration: 9 min
Lesson 17 of 45 · C++
Duration: 9 min
Printable interface\ncpp\nclass Printable {\npublic:\n virtual void print(std::ostream& os) const = 0;\n virtual ~Printable() = default;\n};\n\nclass Person : public Printable {\n std::string name;\n int age;\npublic:\n Person(std::string n, int a) : name(std::move(n)), age(a) {}\n void print(std::ostream& os) const override {\n os << \"Person: \" << name << ", age " << age;\n }\n};\n\nint main() {\n Person p(\"Bob\", 30);\n p.print(std::cout);\n std::cout << '\\n';\n return 0;\n}\n\n\nIf 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.\n\n> Tip: Keep interfaces minimal – only pure virtual functions and a virtual destructor.\n\n---\n\n<Alert type="info">Abstract classes can contain non‑virtual helper functions and data members, offering a blend of concrete and abstract behaviour.