skip to content

In C++, how do delegating constructors and inheriting constructors (using Base::Base) differ in what they initialise and in when the object counts as constructed?

level: seniorimportance: should knowfreq 45%

answer

  1. same class versus base class
  2. delegation must stand alone
  3. destructor after the target returns
  4. inherited: explicit and access kept
  5. derived members get defaults only

basics

~20 s

A delegating constructor hands initialisation to another constructor of its class; after the target returns the object exists, so a throw in the delegating body runs the destructor. An inherited constructor builds the base; derived members get only their defaults.

solid answer

~50 s

A **delegating constructor**, `Connection(int fd, bool fail) : Connection(fd) {}`, names its own class as the only mem-initializer; Clang rejects anything beside it with `an initializer for a delegating constructor must appear alone`. The target runs first, then the delegating body. Because the target has completed, the object counts as constructed: if the delegating body throws, the object's destructor is invoked, unlike a throw from a non-delegating body. An **inheriting constructor**, `using Connection::Connection;` in `TlsConnection`, makes the base's constructors usable to build the derived class: the base subobject is initialised by the inherited constructor and every derived member is initialised as a defaulted default constructor would, so a member with no default member initializer is left default-initialised. Inherited constructors keep their `explicit` and their access, the base's default, copy and move constructors are not usable that way, and a derived constructor with the same signature hides the inherited one.

code

cpp · 21 lines
cpp
#include <cstdio>
#include <stdexcept>

class Connection {
public:
    explicit Connection(int fd) : fd_(fd) { std::puts("target done"); }
    Connection(int fd, bool failHandshake) : Connection(fd) {   // delegating
        if (failHandshake) throw std::runtime_error("handshake");
    }
    ~Connection() { std::printf("close fd %d\n", fd_); }
private:
    int fd_;
};

int main() {
    try {
        Connection c(3, true);
    } catch (const std::exception& e) {
        std::printf("caught %s\n", e.what());
    }
}

go deeper

for a junior

Recall that one constructor can call another of the same class, and that using Base::Base reuses a base class's constructors.

for a middle

Explain the delegation-alone rule and that derived members get only their default member initializers under an inherited constructor.

for a senior

Use the rule that the destructor runs if a delegating body throws, and catch inherited constructors leaving new members uninitialised or exposing unwanted base constructors.

for a principal

Decide where inheriting constructors are acceptable, thin wrappers and test subclasses, and where a derived type must own its construction logic.

## Two features that look alike Both were added in C++11 to cut repetition between constructors, and both use a constructor written elsewhere. They solve different problems: | | Delegating constructor | Inheriting constructor | |---|---|---| | Syntax | `Connection() : Connection(5432) {}` | `using Connection::Connection;` | | Reuses a constructor of | the same class | a direct base class | | What else is initialised | nothing: the target does it all | derived members, by their default member initializers or default-initialisation | | Has its own body | yes, run after the target returns | no | ## Delegating constructors A constructor whose mem-initializer-list names its own class is a **delegating constructor**, and the constructor it selects by overload resolution is the **target constructor**. The rules are strict: - The delegation must be the **only** mem-initializer. Apple clang 21 rejects `C() : C(1), b(2) {}` with `error: an initializer for a delegating constructor must appear alone`. - The target runs completely, then the delegating constructor's body executes. - A constructor that delegates to itself, directly or through a cycle, makes the program ill-formed with no diagnostic required. The subtle part is **when the object exists**. Normally an exception from a constructor body means the object never finished construction, so its destructor is not called; only the already-built members and bases are destroyed. With delegation, the target has already completed a full construction, so the standard says that if the delegating constructor's body exits via an exception, the object's destructor is invoked. The code example shows it: ```plaintext target done close fd 3 caught handshake ``` The destructor ran (`close fd 3`) even though the delegating constructor threw. This lets a class put resource acquisition in a simple target constructor and riskier steps in delegating ones, knowing cleanup will run. It also means the destructor must cope with an object that the delegating body only partly configured. ## Inheriting constructors A using-declaration that names a base's constructor makes the derived class inherit that set of constructors. For `TlsConnection : public Connection` with `using Connection::Connection;`: - `TlsConnection a("db.internal", 6432);` calls `Connection(std::string, int)` for the base subobject. - The rest of `TlsConnection` is initialised as if by a **defaulted default constructor**: `bool verified_ = true;` gets its default member initializer, and a member with none is default-initialised, which leaves an `int` indeterminate. - The inherited constructor keeps its **explicit** specifier: `TlsConnection t = std::string("x");` fails with the note `explicit constructor is not a candidate`. - It keeps its **access**: an inherited protected base constructor used from outside fails with `calling a protected constructor of class 'Connection'`. - The base's copy and move constructors are excluded when constructing the derived type from one argument of a related type, and the derived class's own default, copy and move constructors are still the implicitly declared ones. In a reduced test whose base has no default constructor, `Tls c;` fails with `call to implicitly-deleted default constructor of 'Tls'`. - A constructor the derived class declares with the same parameters **hides** the inherited one. ## When to use which Use delegation when several constructors of one class share setup, especially when the shared part acquires a resource and cleanup must be guaranteed. It replaces the pre-C++11 habit of a private `init()` helper called from every constructor, which could only assign members in the body, never initialise `const` members or references, and gave no destructor guarantee. Use inheriting constructors for **thin derived classes** that add behaviour or members with defaults but no new construction logic, such as a strong-type wrapper or a test subclass. Signs that inheriting constructors are the wrong tool: 1. The derived class adds members that need **constructor arguments**; they will silently get defaults. 2. The derived class must **validate** something on construction; inherited constructors have no derived body. 3. The base has constructors you do **not** want exposed on the derived type; a using-declaration brings in the whole set. ## How to answer Contrast them by who does the work (the same class versus a base), by what happens to derived members (nothing versus defaults only), and by the lifetime rule: after a delegating target returns, the object is constructed, and a throw from the delegating body runs the destructor.

  • In C++, can a delegating constructor also initialise one extra member in its initializer list?
    No. If the mem-initializer names the constructor's own class, it must be the only mem-initializer; Clang reports that an initializer for a delegating constructor must appear alone. Set the extra member in the delegating body, or move it into the target constructor or a default member initializer.
  • A C++ derived class uses using Base::Base; and adds int retries_; with no initializer. What value does retries_ have after construction?
    An indeterminate one. When an inherited constructor initialises the derived object, every other subobject is initialised as a defaulted default constructor would, and for an `int` with no default member initializer that means no initialisation. Reading it is undefined behaviour in C++23. Add `int retries_ = 0;` or write a real constructor.

  • A delegating constructor may initialise extra members alongside the delegation.
  • If a delegating constructor's body throws, the destructor never runs.
  • Inheriting constructors also forward arguments to the derived class's new members.
  • Inherited constructors lose explicit and become implicit conversions.
  • using Base::Base makes the base's protected constructors public in the derived class.