2

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.

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Yep, I was just writing my own answer, you just were 30 seconds faster :P I'll accept it in 5 minutes
@DarkZeros, to add to this answer, I would suggest that you may initialize the member variables with -1 to have the default values.
While you don't need semicolons after function definitions, as said, you do need a semicolon after the class definition.
Yes, I know, I was just copy pasting and missed that, but my code does work. Thanks!
With NSDMIs you'll need C++14 to use aggregate initialization.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.