Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic constructor inheritance in C++20 [duplicate]

I just have this code, and I wonder why this code compiles in C++20 and later, but it doesn't compile in C++17 and earlier.

struct B {
  B(int){};
};

struct D : B {
};

int main() {

  D d = D(10);

}

I know that inheriting constructors is a C++11 feature. But class D doesn't inherit the B::B(int) constructor, even though this line D d = D(10); compiles. My question is, why does it compile only in C++20 and not in C++17? Is there a quote to the C++ standard that applies here?

I am using g++11.2.0.

like image 781
mada Avatar asked Jun 08 '26 15:06

mada


2 Answers

C++20 added the ability to initialize aggregates using parentheses; see P0960. Previously, you could have initialized d using D d{10};; now you can do the same thing with parentheses instead of braces. The class D does not implicitly inherit constructors from B.

like image 161
Brian Bi Avatar answered Jun 11 '26 03:06

Brian Bi


Since struct D is an aggregate type, before C++20 you could not use () for initialization such as D(10).

Thanks to P0960, now in C++20 you can initialize aggregates from a parenthesized list of values. Note that currently, only later versions of GCC-10 and MSVC-19.28 implement this feature, for Clang it will still complain

<source>:15:9: error: no matching conversion for functional-style cast from 'int' to 'D'
  D d = D(10);
        ^~~~
like image 29
康桓瑋 Avatar answered Jun 11 '26 04:06

康桓瑋