skip to content

In a C++ diamond with a virtual StreamBase, why is InputStream's StreamBase(fd) initializer ignored when an IOStream is constructed?

level: seniorimportance: should knowfreq 45%

answer

  1. one shared subobject, one constructor call
  2. the most derived class decides
  3. default constructor if not named
  4. virtual bases go first

basics

~20 s

A virtual base is constructed once, by the most derived class. InputStream's and OutputStream's StreamBase initializers are skipped; IOStream's own initializer is used, or StreamBase's default constructor if IOStream names none, and compilation fails when there is none.

solid answer

~50 s

With `InputStream : virtual StreamBase` and `OutputStream : virtual StreamBase`, `IOStream` has one shared `StreamBase`, so only one constructor can run for it. The standard gives that job to the **most derived class**: a mem-initializer naming a virtual base is ignored in the constructor of any class that is not the most derived. So `IOStream() : InputStream(3), OutputStream(4) {}` constructs `StreamBase` with its **default constructor**, and `fd` ends up `-1`, not 3 or 4. To pass a value, `IOStream` names the virtual base itself: `IOStream(int f) : StreamBase(f), InputStream(f), OutputStream(f) {}`. If `StreamBase` has no default constructor and `IOStream` does not name it, the program does not compile. Virtual bases are also constructed **first**, before any non-virtual base. And a pointer to a virtual base cannot be `static_cast` down to the derived class; that needs `dynamic_cast`.

code

cpp · 27 lines
cpp
#include <iostream>

struct StreamBase {
    int fd;
    explicit StreamBase(int f = -1) : fd(f) { std::cout << "StreamBase(" << f << ")\n"; }
};
struct InputStream : virtual StreamBase {
    explicit InputStream(int f) : StreamBase(f) { std::cout << "InputStream\n"; }
};
struct OutputStream : virtual StreamBase {
    explicit OutputStream(int f) : StreamBase(f) { std::cout << "OutputStream\n"; }
};
struct IOStream : InputStream, OutputStream {
    IOStream() : InputStream(3), OutputStream(4) { std::cout << "IOStream\n"; }
    explicit IOStream(int f) : StreamBase(f), InputStream(f), OutputStream(f) {
        std::cout << "IOStream\n";
    }
};

int main() {
    IOStream a;            // StreamBase not named: default-constructed
    std::cout << "a.fd = " << a.fd << "\n\n";
    IOStream b(7);         // most derived class initializes the virtual base
    std::cout << "b.fd = " << b.fd << '\n';
    StreamBase* base = &b; // unambiguous now: one shared subobject
    std::cout << (base == static_cast<InputStream*>(&b)) << '\n';
}

go deeper

for a junior

Recall that a virtual base is shared, so it is constructed exactly once, and that the class being created as a whole is the one that constructs it.

for a middle

State the rule from the standard: virtual-base mem-initializers are ignored unless the class is most derived, with default construction as the fallback.

for a senior

Walk through the construction order, the static_cast restriction, and the production trap where a unit test of a middle class takes a different initializer path.

for a principal

Weigh whether a stateful virtual base is worth the coupling it creates, since every future most derived class must know how to construct it.

## One subobject, one constructor call **Virtual inheritance** exists so that a diamond shares a single copy of its top class: ```cpp struct InputStream : virtual StreamBase { explicit InputStream(int f) : StreamBase(f) {} }; struct OutputStream : virtual StreamBase { explicit OutputStream(int f) : StreamBase(f) {} }; struct IOStream : InputStream, OutputStream { /* ... */ }; ``` There is one `StreamBase` inside an `IOStream`, but two middle constructors each ask to initialize it with their own argument. Only one constructor call can run for one subobject, and neither middle class knows about the other. C++ resolves this by giving the job to whichever class is being constructed as the complete object. ## The rule: the most derived class constructs virtual bases The **most derived class** is the type of the complete object being created. The standard says that a mem-initializer naming a virtual base class is **ignored** during the constructor of any class that is not the most derived class. Concretely: 1. When an `InputStream` is created on its own, `InputStream` is most derived, and its `StreamBase(f)` runs. 2. When an `IOStream` is created, `IOStream` is most derived. The `StreamBase(f)` in `InputStream`'s and `OutputStream`'s initializer lists is skipped. 3. If `IOStream`'s constructor names `StreamBase(...)`, that initializer is used. If it does not, `StreamBase` is **default-initialized**, which for a class means its default constructor runs. 4. If `StreamBase` has no default constructor and `IOStream` does not name it, the program is ill-formed. Clang says: `constructor for 'IOStream' must explicitly initialize the base class 'StreamBase' which does not have a default constructor`. The code example makes it visible. `IOStream a;` prints `StreamBase(-1)` and ends with `fd == -1`, although the middle classes passed 3 and 4. `IOStream b(7);`, whose constructor names `StreamBase(7)`, prints `StreamBase(7)` and ends with `fd == 7`. An **abstract class** can never be the most derived class, so its constructors never initialize virtual bases; the standard notes that an abstract class may therefore omit those mem-initializers entirely. Interface-style middle classes often rely on that. ## Construction order In a constructor of the most derived class, initialization proceeds in this order: | Step | What is initialized | |---|---| | 1 | virtual bases, depth-first left-to-right over the inheritance graph | | 2 | direct non-virtual bases, in base-specifier-list order | | 3 | non-static data members, in declaration order | | 4 | the constructor body | The order of the mem-initializers you write never changes this. For the diamond, the output reads `StreamBase`, `InputStream`, `OutputStream`, `IOStream`, with `StreamBase` exactly once. Destruction runs in the reverse order, so the shared base is destroyed last. ## Casting back down from a virtual base Where a virtual base sits inside the complete object depends on the **dynamic type**: in a standalone `InputStream` the `StreamBase` is at one offset, inside an `IOStream` at another. A `static_cast` must compute the adjustment at compile time, so the standard makes a `static_cast` from a pointer or reference to a virtual base, down to a derived class, **ill-formed**. Clang: `cannot cast 'StreamBase *' to 'IOStream *' via virtual base 'StreamBase'`. A `dynamic_cast` works, provided `StreamBase` is polymorphic, because it looks up the complete object at run time. Implementations reach virtual bases through an offset stored at run time, commonly in the virtual table; the details belong to the material on vtables. ## Consequences for real hierarchies - Every class that may become most derived must know about every virtual base above it, including ones several levels up. Adding a virtual base to a widely used middle class silently changes which constructor arguments matter. - A virtual base with a constructor parameter forces all derived classes to pass it, which is why designs with virtual bases often give the shared base a default constructor or no state at all. - Tests that construct the middle classes on their own exercise a different initializer than production code that constructs the bottom class. A value that "works in the unit test" can be ignored in the full object. The standard library's iostreams show one way to live with this rule. `std::basic_ios`, the virtual base of the diamond, has a protected default constructor, and the stream constructors set it up by calling its protected `init` member, so the design does not depend on which class happens to be most derived.

  • In C++, what happens when a fourth class derives from IOStream and does not name the virtual StreamBase in its constructor?
    The new class is now the most derived class, so it alone initializes `StreamBase`. `IOStream`'s own `StreamBase(f)` initializer is ignored for these objects, and `StreamBase` is default-initialized. If `StreamBase` has no default constructor, the new class fails to compile until its constructor names `StreamBase(...)` explicitly.
  • In what order are a C++ IOStream's base subobjects destroyed when StreamBase is a virtual base?
    Destruction is the exact reverse of construction: the `IOStream` destructor body runs, then its members, then `OutputStream`, then `InputStream`, and finally the shared virtual `StreamBase`, once. Because the virtual base is constructed first, it is destroyed last, so the middle classes can still use it in their destructors.

Roommates who each wrote a move-in date into their own sublease: the building only honours the head lease signed by the main tenant. Whoever signs as the main tenant decides, and the subleases' dates are ignored even though they are written down.

  • The first base listed constructs the shared virtual base.
  • Each middle class constructs its own copy of the virtual base.
  • The last StreamBase initializer to run overwrites the earlier one.
  • A static_cast can convert a virtual base pointer back to the derived class.
  • Mem-initializer order in the constructor decides construction order.