简体   繁体   中英

Inheriting constructors in C++20 (Visual Studio 2019)

I am using Visual Studio 2019 (v16.10.3) with /std:c++latest and this compiles:

class Base
{
public:
   Base(int x) {}
};

class Derived : public Base
{
// no constructors declared in Derived
};

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

For the previous versions of the standard I have to declare inherited constructors with the using directive:

class Derived : public Base
{
   using Base::Base;
};

Is this something new that was put in C++20 or is it some Microsoft specific thing?

Is this something new that was put in C++20 or is it some Microsoft specific thing?

Not with relation to inherited constructors. What changed is that aggregate initialization may use parenthesis under certain conditions. Derived is considered an aggregate on account of having no private parts, so we initialize its bases and members directly.

It even works when we add a public member:

class Base
{
public:
   Base(int ) {}
};

struct Derived : public Base
{
// no constructors declared in Derived
    int y;
};

int main() {
   Derived d(5, 4);
}

Live

This is the result of C++17 allowing classes with base classes to still be considered aggregates combined with C++20 rules allowing aggregate initialization to work with () constructor syntax if the values in the parentheses would work (and wouldn't call a constructor). So while it looks like a constructor call, it's actually aggregate initialization.

Derived doesn't have a constructor matching Base 's constructor; you're merely initializing the aggregate Derived by providing a valid initializer for its subobject Base .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM