Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/65919790/c-why-base-class-struct-constructor-cant-have-more-than-one-argument-to-be-im

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...