Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Do C++20 structs have a compiler-generated constructor with parameters?

I was surprised to see that this compiles in C++20 (GCC):

#include <iostream>

struct Test {
    int a;
    int b;
};

void main() {
    Test myTest(1, 2);
    std::cout << myTest.b; // 2
}

Changing struct to class or switching to C++17 throws the error I expected:

error: no matching function call to 'Test::Test(int, int)'

I tried googling, but could not find anything relevant. In C++20, is there a new kind of compiler-generated constructor for structs?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is p0960r3, which allows aggregate initialization from a parenthized list of values. struct or class is (as typically) a red herring here: your original struct Test class is an aggregate, but when you change its members to fall under private access rules it is no longer an aggregate. The rules for aggregates and aggregate initialization are notoriously ever-changing as the language evolves, see e.g. The Fickle Aggregate for details.

I tried googling, but could not find anything relevant.

If you find a new feature of a given language version, and you do not understand how or why it was introduced, the open-std delta pages can be a good place to start:

Changes between C++17 and C++20 DIS

[…]

(P0960R3, P1975R0) Aggregate initialization from a parenthesized list

Aggregates can now be initialized with round parentheses instead of curly braces: struct T { int a, b, c; }; T x(1, 2); A (motivating) consequence is that make_unique and emplace now work with aggregate types.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading