Skip to content
Tutorials Center
My learning

Topics

Lesson 80 of 171 ยท Object-Oriented Programming

Abstract Classes and Interfaces

Learn C++ abstract classes - pure virtual functions, interfaces as abstract classes, programming to an interface, and factory functions that return unique_ptr<Base>.

Some base classes describe an idea that has no sensible default behavior. What's the area of "a shape"? How does "a payment method" charge a card? In Virtual Functions and Polymorphism, the base class Shape returned 0.0 from area() just to have something. That's a lie waiting to cause a bug: a class that forgets to override area() silently reports zero.

C++ lets you say what you really mean: "every shape must provide area(), and there is no such thing as a plain shape". You do that with pure virtual functions, and a class that has one is an abstract class. You can't create objects of it; you can only derive from it. An abstract class made of nothing but pure virtual functions is what other languages call an interface. This lesson shows how to declare them, how they shape good designs (programming to an interface, swapping in test doubles, the template method pattern), and the standard way to create objects behind an interface: factory functions returning std::unique_ptr<Base>.

Pure virtual functions

Write = 0 after a virtual function's declaration to make it pure virtual. It says: "this class declares the function, but derived classes must define it."

C++ An abstract Shape

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Uncomment Shape s; and the compiler refuses, and it even lists which pure virtual functions make Shape abstract. The rules:

  • A class with at least one pure virtual function (declared or inherited and not overridden) is abstract. You can't create objects of it, take it by value, or return it by value.
  • You can have pointers and references to an abstract class. That's the whole point: code works with Shape& and never needs to know the concrete type.
  • A derived class that doesn't override every pure virtual function is abstract too. That's useful for intermediate classes, and a helpful compile error when you forget one.
  • Abstract classes can still have data members, constructors and ordinary member functions, like report() above. A non-pure member calling a pure virtual one is perfectly normal: by the time anyone can call report(), the object is a concrete Circle or Rectangle.

Because Shape can only ever be a base class subobject, its constructor is often made protected. That documents intent; the class is already uninstantiable because of the pure virtual functions.

A pure virtual function can still have a body

= 0 means "derived classes must override this", not "this has no code". You may define a pure virtual function outside the class, and derived classes can call it explicitly as a shared default:

C++
class Logger {
public:
    virtual ~Logger() = default;
    virtual void write(const std::string& line) = 0;
};

void Logger::write(const std::string& line) {        // body for the pure virtual
    std::println("[{}] {}", timestamp(), line);
}

class ConsoleLogger : public Logger {
public:
    void write(const std::string& line) override { Logger::write(line); }   // opt in
};

The one place this is required is a pure virtual destructor, virtual ~Base() = 0;, sometimes used to make a class abstract when it has no other natural pure virtual function. Every derived destructor calls the base destructor, so it still needs a definition: Base::~Base() = default; written outside the class (or inline in a header).

Interfaces

C++ has no interface keyword. An interface is simply a class with:

  • only pure virtual member functions,
  • a public virtual destructor (so objects can be deleted through it),
  • no data members.

Because interfaces carry no data, a class can implement several of them through multiple inheritance with none of the diamond problems described in Access in Inheritance, Multiple and Virtual Inheritance.

C++ One class, two interfaces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

render needs only "something drawable", and save needs only "something serializable". Neither depends on Button, and each accepts any future class that implements its interface. This is the interface segregation idea: many small interfaces beat one huge base class that forces every implementer to provide functions it doesn't need.

Programming to an interface

The biggest benefit of interfaces shows up in the classes that use them. If a class depends on an interface instead of a concrete class, you can give it a different implementation without changing its code: a real email sender in production, a fake one in tests.

C++ Swapping implementations behind an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

OrderService receives its dependency through the constructor (this is called dependency injection). It holds a reference here because main owns both objects and outlives the service. When the service should own its dependency, store a std::unique_ptr<Notifier> instead.

Factory functions returning unique_ptr

Code that works through an interface still has to create the concrete objects somewhere. Gather that knowledge in one place, a factory function, which decides which class to instantiate and returns ownership as a std::unique_ptr<Base> (see Smart Pointers: std::unique_ptr). Everything else in the program only sees the interface.

This example reads shape descriptions from the Input box. The factory turns each line into the right object, or reports an error for unknown kinds.

C++ A shape factory driven by input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The factory returns nullptr for input it doesn't understand, and main checks for it. Returning std::unique_ptr<Shape> makes the ownership rules impossible to miss: the caller owns the new object, it can't leak, and when the vector is destroyed every shape is deleted through Shape's virtual destructor. Other reasonable error strategies are throwing an exception or returning std::expected (see Error Handling Without Exceptions).

Larger programs often replace the if chain with a registry, for example a std::map<std::string, std::function<std::unique_ptr<Shape>(double, double)>>, so new shape types can register themselves without editing the factory.

The template method pattern

Abstract classes don't have to be pure interfaces. A common design puts the algorithm in a non-virtual public function of the base class and lets derived classes fill in the steps by overriding private pure virtual functions. This is the template method pattern; in C++ it's also called the non-virtual interface (NVI) idiom.

C++ Non-virtual interface with private hooks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Yes, a derived class can override a private virtual function. Access control decides who may call a function, not who may override it. The base class keeps control of the sequence (header, body, footer), which is a convenient place for logging, locking or checks that every implementation must get, while derived classes supply only the varying parts.

Interface design tips

  • Give every interface a virtual destructor, usually virtual ~Name() = default;. Without it, deleting through the interface is undefined behavior.
  • Prevent slicing and accidental copies. Copying through an interface makes no sense. Many codebases declare the copy operations of interfaces protected or = delete.
  • Keep interfaces small and focused. Two three-function interfaces are easier to implement and fake than one ten-function interface.
  • Name them after the capability: Drawable, Notifier, Clock, Storage. Prefixes like IStorage are a convention in some codebases; follow whatever your project uses.
  • Consider templates when the type is known at compile time. Virtual functions give runtime polymorphism: the concrete type can be chosen while the program runs, as in the factory above. If it's always fixed at compile time, a template constrained by a concept (see Concepts and Constraints) avoids the virtual calls and the heap allocations.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. class Shape { public: virtual double area() const = 0; }; What does Shape s; do?

    A class with a pure virtual function is abstract. You can't create objects of it, only pointers and references to it.
  2. 2. Square derives from the abstract Shape (pure virtual area() and name()) but overrides only area(). What is true?

    A class stays abstract until every inherited pure virtual function is overridden. Defining Square is fine; creating a Square object is the error.
  3. 3. Why does a factory function typically return std::unique_ptr<Shape> rather than Shape?

    An abstract class can't be returned by value, and returning a concrete class as a base value would slice it. A unique_ptr<Shape> keeps the real object and gives the caller clear ownership.
  4. 4. In the non-virtual interface idiom, the hook functions are private virtual. Can a derived class override them?

    A derived class can override a private virtual function. It just can't call the base's version, and outside code can't call the hook directly, which keeps the algorithm in the base class's public function.
  5. 5. Which declaration makes a class abstract and still requires a definition elsewhere?

    A pure virtual destructor makes the class abstract, but every derived destructor calls it, so it needs a definition such as Base::~Base() = default;.

Summary

  • virtual f() = 0; declares a pure virtual function. A class with any pure virtual function (declared or inherited and not overridden) is abstract and can't be instantiated.
  • Abstract classes can have data, constructors and normal functions. A pure virtual function may even have a body, and a pure virtual destructor must have one.
  • An interface in C++ is an abstract class with only pure virtual functions, a virtual destructor and no data. Implementing several interfaces is safe and common.
  • Write classes against interfaces and inject the implementation, so you can swap production code for test doubles without changes.
  • Factory functions concentrate the knowledge of concrete classes and return std::unique_ptr<Base>.
  • The non-virtual interface idiom keeps the algorithm in a public non-virtual function and lets derived classes override private virtual steps.

Next: RTTI, dynamic_cast and typeid, for the rare cases when code must find out an object's real type.