Lesson 3 of 6
Abstract Classes & Interface Design
A class with at least one **pure virtual function** (`= 0`) is **abstract** - it cannot be instantiated. Abstract classes define interfaces (contracts) that derived classes must fulfill. In modern C++, good interface design uses pure virtual destructors carefully, provides non-virtual public functions that call virtual private hooks (NVI pattern), and avoids fragile base class problems with `final`.
Abstract Classes, NVI Pattern & Interface Segregation
Abstract Classes, NVI Pattern & Interface Segregation
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <memory>
// ── Interface - pure abstract class ──────────────────────────
class ISerializable {
public:
virtual ~ISerializable() = default;
virtual std::string serialize() const = 0;
virtual void deserialize(const std::string& data) = 0;
};
class IRenderable {
public:
virtual ~IRenderable() = default;
virtual void render(int x, int y) const = 0;
};
// ── NVI (Non-Virtual Interface) pattern ───────────────────────
// Public non-virtual function = stable interface
// Private virtual function = customisation point
class Logger {
public:
virtual ~Logger() = default;
// Public API - non-virtual, stable, provides pre/post logic
void log(const std::string& message) {
if (message.empty()) return; // common validation
do_log("[" + prefix() + "] " + message); // calls hook
}
const std::string& name() const { return name_; }
protected:
explicit Logger(std::string name) : name_(std::move(name)) {}
private:
std::string name_;
virtual std::string prefix() const { return name_; } // default
virtual void do_log(const std::string& msg) = 0; // pure hook
};
class ConsoleLogger : public Logger {
public:
explicit ConsoleLogger(std::string name) : Logger(std::move(name)) {}
private:
void do_log(const std::string& msg) override {
std::cout << msg << "
";
}
};
class TaggedLogger : public Logger {
std::string tag_;
public:
TaggedLogger(std::string name, std::string tag)
: Logger(std::move(name)), tag_(std::move(tag)) {}
private:
std::string prefix() const override { return Logger::name() + "/" + tag_; }
void do_log(const std::string& msg) override {
std::cout << "[32m" << msg << "[0m
"; // green colour
}
};
// ── Multiple interface implementation ─────────────────────────
class Widget : public IRenderable, public ISerializable {
int x_, y_;
std::string label_;
public:
Widget(int x, int y, std::string label)
: x_(x), y_(y), label_(std::move(label)) {}
void render(int x, int y) const override {
std::cout << "Widget[" << label_ << "] at (" << x+x_ << "," << y+y_ << ")
";
}
std::string serialize() const override {
return "Widget:" + label_ + ":" + std::to_string(x_) + "," + std::to_string(y_);
}
void deserialize(const std::string& data) override {
// simplified parsing
std::cout << "Deserializing: " << data << "
";
}
};
int main() {
// Cannot instantiate abstract class
// IRenderable r; ← compile error: has pure virtual functions
ConsoleLogger cl{"App"};
TaggedLogger tl{"App", "NET"};
cl.log("Starting up"); // [App] Starting up
tl.log("Connected"); // [App/NET] Connected
Widget w{10, 20, "Button"};
w.render(0, 0);
std::cout << w.serialize() << "
";
// Polymorphic use via interface pointer
IRenderable* r = &w;
r->render(5, 5); // virtual dispatch
return 0;
}Diagram
Loading diagram…
Enforcing Contracts with Pure Virtual Functions (= 0) and Concrete Class Implementation
Common Mistakes
- Forgetting to implement ALL pure virtual functions in derived - if `Circle` misses implementing any pure virtual from `Shape`, `Circle` is also abstract. Attempting `Circle c;` gives 'cannot instantiate abstract type Circle'.
- Returning raw pointer from factory functions - `Shape* create()` - callers must remember to `delete`. Return `std::unique_ptr<Shape>` from factory functions for automatic ownership.
- NVI with public virtual - mixing public virtual functions with the NVI pattern defeats the purpose. The NVI point is: public=stable interface (non-virtual), private virtual=customisation hook. If both are virtual and public, there's no stable interface layer.
Key Takeaways
- A class with at least one **pure virtual function** (`= 0`) is **abstract** - it cannot be instantiated.
- Forgetting to implement ALL pure virtual functions in derived - if `Circle` misses implementing any pure virtual from `Shape`, `Circle` is also abstract. Attempting `Circle c;` gives 'cannot instantiate abstract type Circle'.
- Returning raw pointer from factory functions - `Shape* create()` - callers must remember to `delete`. Return `std::unique_ptr<Shape>` from factory functions for automatic ownership.
- NVI with public virtual - mixing public virtual functions with the NVI pattern defeats the purpose. The NVI point is: public=stable interface (non-virtual), private virtual=customisation hook. If both are virtual and public, there's no stable interface layer.
Finished this lesson?
0 of 6 in Module 4