In C++, if InputStream and OutputStream both inherit StreamBase non-virtually, what does an IOStream deriving from both contain, and what breaks?
answer
- count the base subobjects
- two copies of every data member
- unqualified access is ambiguous
- virtual on the edges into the shared base
basics
~20 sIOStream contains two separate StreamBase subobjects, one per path. Unqualified use of a StreamBase member and conversion to StreamBase* are ambiguous, and the two copies can drift apart. Virtual inheritance in InputStream and OutputStream makes them share one.
solid answer
~40 sWith ordinary (non-virtual) inheritance every base is a separate **subobject**, so `IOStream : InputStream, OutputStream` holds **two** `StreamBase` subobjects: one inside `InputStream`, one inside `OutputStream`. Consequences: `io.fd` does not compile, because the member is found in two `StreamBase` subobjects; `StreamBase* b = &io;` is an ambiguous conversion; you must pick a path, as in `io.InputStream::fd` or `static_cast<InputStream*>(&io)`; and the two copies hold independent state, so one path can see `fd == 3` while the other sees `4`. The fix is **virtual inheritance** written on the edges into the shared base: `struct InputStream : virtual StreamBase` and `struct OutputStream : virtual StreamBase`. Then `IOStream` has exactly one `StreamBase`. Marking `IOStream`'s own bases virtual does not help.
code
cpp · 21 lines#include <iostream>
struct StreamBase {
int fd = -1;
explicit StreamBase(int f = -1) : fd(f) {}
};
struct InputStream : StreamBase { using StreamBase::StreamBase; };
struct OutputStream : StreamBase { using StreamBase::StreamBase; };
struct IOStream : InputStream, OutputStream {
IOStream() : InputStream(3), OutputStream(4) {}
};
int main() {
IOStream s;
std::cout << s.InputStream::fd << ' ' << s.OutputStream::fd << '\n';
std::cout << sizeof(StreamBase) << ' ' << sizeof(IOStream) << '\n';
// s.fd; // error: ambiguous
// StreamBase* b = &s; // error: ambiguous conversion
StreamBase* in_side = static_cast<InputStream*>(&s); // pick a path
std::cout << in_side->fd << '\n';
}go deeper
Recall that a non-virtual diamond gives the bottom class two copies of the top base, and that unqualified access to its members stops compiling.
Explain subobjects, the two ambiguity errors, how to name a path, and that virtual goes on every edge into the shared base.
Point out the silent failure: qualified code compiles while the two copies diverge, and show how the iostream hierarchy plans its diamond in advance.
Argue when a diamond of stateful classes is worth designing for at all, since the middle-class authors must opt in before the bottom class exists.
## The shape of the diamond The **diamond** is the inheritance graph you get when two classes derive from a common base and a third class derives from both: ```cpp struct StreamBase { int fd = -1; }; struct InputStream : StreamBase { }; struct OutputStream : StreamBase { }; struct IOStream : InputStream, OutputStream { }; ``` Drawn as a graph, `StreamBase` sits at the top, `InputStream` and `OutputStream` in the middle, `IOStream` at the bottom. The question is what the bottom object physically contains. ## Ordinary inheritance duplicates the base In C++, each non-virtual base class is a distinct **base class subobject** of the derived object. `InputStream` contains a `StreamBase`; `OutputStream` contains another; `IOStream` contains both middle classes and therefore **two `StreamBase` subobjects**. The graph is a diamond, but the object is not: it is two separate chains glued together. The code example shows it. The constructor gives each path its own descriptor, and `io.InputStream::fd` prints `3` while `io.OutputStream::fd` prints `4`. On that build `sizeof(StreamBase)` is 4 and `sizeof(IOStream)` is 8: the `int` is stored twice. Exact sizes are the implementation's choice, but the duplication is the language's rule. ## What stops compiling | Expression | Result with two `StreamBase` subobjects | |---|---| | `io.fd` | error: member found in multiple base-class subobjects | | `StreamBase* b = &io;` | error: ambiguous conversion to base class | | `io.InputStream::fd` | fine: the path is named | | `static_cast<InputStream*>(&io)` then to `StreamBase*` | fine: one path chosen | Clang words the first two as `non-static member 'fd' found in multiple base-class subobjects of type 'StreamBase'` and `ambiguous conversion from derived class 'IOStream' to base class 'StreamBase'`. A `dynamic_cast<StreamBase*>(&io)` is rejected the same way, because an up-conversion to an ambiguous base is ill-formed whichever cast spells it. Static members, nested types and enumerators of `StreamBase` remain usable unqualified: the standard notes that only non-static members are ambiguous, since the others do not live in a subobject. ## The quieter bug: diverging state The compile errors are the friendly part. Code that does name a path compiles, and then the two copies drift apart: a `close()` called through the `InputStream` side resets one `fd`, while a write through the `OutputStream` side still uses the other. Nothing reports it; the object simply holds two answers to "which descriptor am I?". ## The fix: virtual inheritance Declaring the base **virtual** on the edges that lead into it makes all such edges share one subobject: ```cpp struct InputStream : virtual StreamBase { }; struct OutputStream : virtual StreamBase { }; struct IOStream : InputStream, OutputStream { }; // one StreamBase ``` Points that are easy to get wrong: - The keyword goes on the classes that derive **directly** from the shared base. Writing `struct IOStream : virtual InputStream, virtual OutputStream` still leaves two `StreamBase` subobjects; a quick run confirms that writing through one path leaves the other at `-1`. - **Every** path must say `virtual`. If only `InputStream` does, `IOStream` holds one virtual `StreamBase` plus the non-virtual one inside `OutputStream`: two again. - The decision is made by the authors of the middle classes, before anyone writes `IOStream`. That is why libraries that expect a diamond plan for it up front. The standard library is the textbook case: `std::basic_istream` and `std::basic_ostream` each derive `virtual public basic_ios<charT, traits>`, and `std::basic_iostream` derives publicly from both, so a `std::iostream` has one `basic_ios` holding one stream state and one buffer pointer. Virtual inheritance has its own rules, chiefly that the most derived class constructs the shared base, and its own costs in object layout and access; those belong to the question about virtual base construction. ## How interviewers probe it 1. Ask how many base subobjects the bottom class holds, and why. 2. Ask what `io.fd` and `&io` to `StreamBase*` do, expecting "ambiguous" rather than "the first base wins". 3. Ask where `virtual` goes, listening for the middle classes rather than the bottom one. 4. Ask for a real example, expecting the iostreams hierarchy rather than an invented zoo of animals. A candidate who can also explain why the duplicate copies are sometimes wanted, for example two independent list hooks inherited from one hook class through two different middle classes, so the object can sit in two lists at once, shows they understand the rule rather than a slogan: non-virtual inheritance means separate subobjects, and sometimes separate is exactly what the design needs.
- Does writing struct IOStream : virtual InputStream, virtual OutputStream remove the duplicate StreamBase in C++?No. That makes `InputStream` and `OutputStream` virtual bases of `IOStream`, which matters only if something else also derives from them. Each still derives non-virtually from `StreamBase`, so `IOStream` keeps two `StreamBase` subobjects. The `virtual` keyword has to sit on the edges into the shared class: `InputStream : virtual StreamBase` and `OutputStream : virtual StreamBase`.
- Which part of the C++ standard library is built as a virtual diamond?The iostreams hierarchy. `std::basic_istream` and `std::basic_ostream` each declare `virtual public basic_ios<charT, traits>`, and `std::basic_iostream` derives publicly from both. A `std::iostream` or `std::fstream` therefore has a single `basic_ios`, so its error state, formatting flags and stream buffer pointer exist once and both the reading and the writing side see the same values.
Two departments that each keep their own copy of the company address book: asking for "the address book" is ambiguous, and an edit in one copy never reaches the other. Virtual inheritance is agreeing, in advance, that both departments use one shared book.
- In a non-virtual diamond, the first listed base's copy silently wins.
- The bottom class must list its bases as virtual to share the top one.
- One middle class saying virtual is enough to merge the copies.
- A diamond always means one shared base subobject in C++.
- dynamic_cast resolves an ambiguous up-conversion to the shared base.