DarkZeros
DarkZeros

Reputation: 8410

Class brace-enclosed initializer list fails

I am having problems initializing this class:

class Table{
public:
    long r; 
    long c;
    int g;
    int q;
    std::vector<std::vector<long> > data;
//Helper Methods
    Table(){r=-1;c=-1;g=-1; q=-1;data.clear();};
    double rate(void) const {...};
    bool check(void) const {...};
    void q_auto(void){q = r / g;};
};

If I try with this:

static Table my_table = {16200, 10800, 360, 30, {{1,3},{2,5}}};

It simply fails with:

error: could not convert ‘{16200, 10800, 360, 30, {{1, 3}, {2, 5}}}’ from ‘<brace-enclosed initializer list>’ to ‘Table’

I do have C++11. So, what is wrong there? I tried with extra braces, but no luck.... I am using g++.

The class was not supposed to be hand-written, but I know the values are correct, and just want to stick the table as a global value. Without any extra internal callings to get the final table values.

Upvotes: 2

Views: 1346

Answers (1)

Sneftel
Sneftel

Reputation: 41464

Brace initialization of the struct members is only available when no user-defined constructors are declared. Since Table has a user-defined default constructor, you're not allowed to initialize the members directly (to keep user code from constructing an instance of the class without the constructor itself being run).

Incidentally, you don't need semicolons after function definitions.

EDIT: Incorporating iammilind's suggestion, a good way to support both default initialization of the members to -1 as well as brace initialization would be as follows:

class Table{
public:
    long r = -1; 
    long c = -1;
    int g = -1;
    int q = -1;
    std::vector<std::vector<long> > data;

    double rate(void) const {...}
    bool check(void) const {...}
    void q_auto(void){q = r / g;}
};

This relies on C++11 support for class member initializers, and C++14 support for brace initialization of classes with member initializers.

Upvotes: 8

Related Questions