Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++20

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?

like image 946
fordcars Avatar asked Apr 25 '26 03:04

fordcars


1 Answers

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.

like image 124
dfrib Avatar answered Apr 27 '26 16:04

dfrib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!