Learning Hub Search Ctrl K

Legacy C++ › 3. Classes and Object-Oriented Programming

Abstract Classes and Interfaces

Pure virtual functions and interface-style design.

intermediate #abstract-class#pure-virtual#interface#polymorphism

Explanation

A class with at least one pure virtual function (virtual void f() = 0;) is abstract: you cannot create objects of it, only of concrete classes that override every pure virtual function. Abstract classes with no data and only pure virtual functions act as interfaces; C++ has no interface keyword.

A pure virtual function may still have a body (callable as Base::f()), and a pure virtual destructor must have a definition because derived destructors call it.

Example

#include <iostream>
#include <string>

class Logger {                                   // interface
public:
    virtual ~Logger() {}
    virtual void log(const std::string& msg) = 0;
};

class ConsoleLogger : public Logger {
public:
    void log(const std::string& msg) { std::cout << "[console] " << msg << "\n"; }
};

class PrefixLogger : public Logger {
    std::string prefix_;
public:
    explicit PrefixLogger(const std::string& p) : prefix_(p) {}
    void log(const std::string& msg) { std::cout << prefix_ << msg << "\n"; }
};

class Service {
    Logger& log_;                                // depends on the interface only
public:
    explicit Service(Logger& l) : log_(l) {}
    void run() { log_.log("service started"); }
};

int main() {
    // Logger l;                                 // error: abstract
    ConsoleLogger c;
    PrefixLogger  p("** ");
    Service(c).run();
    Service(p).run();
    return 0;
}

Common pitfalls

  • A derived class that forgets one pure virtual stays abstract, and new Derived fails with a confusing error.
  • Always give an interface a virtual destructor.
  • Calling a pure virtual function from a base constructor/destructor is undefined behavior.
  • A one-character signature difference (a missing const) means you did not override; the class stays abstract.
  • Do not put data and constructors logic in “interfaces” unless you want a real base class.

Legacy vs modern

C++11 override makes signature mistakes a compile error; = default/= delete clean up special members. Concepts (C++20) and templates provide compile-time polymorphism where a virtual interface is not needed.

Exercises

1. Can an abstract class have a constructor?

Yes. Derived classes call it to initialize the base subobject; you just cannot instantiate the abstract class directly.