Home > Back-end >  Automatic constructor inheritance in C 20
Automatic constructor inheritance in C 20

Time:05-02

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.

CodePudding user response:

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.

CodePudding user response:

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);
        ^~~~
  • Related