user34537
user34537

Reputation:

default constructor for member init?

If I uncomment the line testfn causes a compile error. What constructor can I add using =default to allow me to define the comment out lane and still use TestFn()? Remember t{a} should also work (not shown below).

struct Test2 {
    int a; int*p;
    Test2()=default;
    //Test2(int a, int b, int c){};
};
void TestFn() { Test2 t{5,nullptr}; }

Upvotes: 2

Views: 218

Answers (1)

Potatoswatter
Potatoswatter

Reputation: 137880

The same thing happens if you explicitly define Test2() {}.

That form of initialization is called aggregate initialization and it only applies if there are no user-defined constructors. It does not go through any constructor but rather initializes the members directly from the braced initializer list. So there is nothing to default; you have to define explicitly any constructors you want.

Actually I feel a little surprised the explicitly-defaulted constructor doesn't disable aggregate initialization. According to @juachopanza, C++11 was specifically worded that aggregate initialization be contingent on no definition, allowing specifically for a declaration.

Upvotes: 5

Related Questions