Ashutosh Kumar Ray
Ashutosh Kumar Ray

Reputation: 41

Why am I getting error while initializing a struct with curly braces?

I am using the below code and getting error. I don't understand why I am getting this error.

prog.cpp: In function ‘int main()’:
prog.cpp:15:44: error: could not convert ‘{"foo", true}’ from 
                       ‘<brace-enclosed initializer list>’ to ‘option’
                       option x[] = {{"foo", true},{"bar", false}};
                                            ^
prog.cpp:15:44: error: could not convert ‘{"bar", false}’ from 
                       ‘<brace-enclosed initializer list>’ o ‘option’

The code

#include <iostream>
#include <string>
 
struct option
{
    option();
    ~option();
 
    std::string s;
    bool b;
};
 
option::option() = default;
option::~option() = default;

int main()
{
    option x[] = {{"foo", true},{"bar", false}};
}

Upvotes: 4

Views: 1366

Answers (1)

JeJo
JeJo

Reputation: 32852

When you provide the default constructor and destructor, you are making the struct be a non-aggregate type, hence aggregate initialization is not possible.

However, you can check if a type is an aggregate using the standard std::is_aggregate_v trait. (Since ).

See here for your case. It is not an aggregate, as you provided those constructors.

You have the following three ways to make this work:


The following post explains when the constructor will be defaulted, when it is considered as user-declared and user-provided clearly: (Credits @NathanOliver)

C++ zero initialization - Why is `b` in this program uninitialized, but `a` is initialized?

Upvotes: 6

Related Questions