C++ Why base class/struct constructor can't have more than one argument to be implicitly callable from derived?

Viewed 81

Why this can't work:


struct Base {
    Base(int a, int b) {}
};

struct Derived: Base {
    // using Base::Base; // unless I add this
};

int main() {
    Derived d(0, 0);
}

While this can:


struct Base {
    Base(int a) {}
};

struct Derived: Base {
    // using Base::Base; // without this line
};

int main() {
    Derived d(0);
}

Note: C++20 GCC 10.2 (second example doesn't work in C++17 either)

What's the magic behind the second example in C++20?

2 Answers

The "magic" is that you're accidentally using aggregate initialization. In C++20 (and not before), you can invoke aggregate initialization by using parenthesis instead of curly braces, so long as no actual constructor (like the copy/move constructor) would have been invoked. This was done to allow indirect construction of types (emplace, optional's in-place constructor, make_shared/unique, etc) to work on aggregate types.

Your type Derived is an aggregate, as it has no user-provided constructors and one subobject (the base class). So your use of constructor syntax will invoke aggregate initialization, with the first aggregate member being the base class. Which can be constructed from an int (BTW, it's generally bad form to not make constructors from a single parameter explicit unless they're copy/move constructors).

Generally speaking, unless you are intending to create an aggregate (ie: the type is just an arbitrary bundle of values), derived classes ought to have constructors. I can't recall when I've written a derived class that didn't also have at least one constructor. And if it is your intent for the derived class to have the base class constructors, you should explicitly spell that out whenever you want to do that. Constructors are not inherited without explicit say-so.

The trick is to use a derived constructor.

Derived::Derived(int a, int b) : Base(a, b) {
    ...
}

Non-static members can also be initialized this way.

Related