Why the same statement doesn't work for Class member in C++?

Viewed 54

I'm very new to C++ and below is my program. It defines a nested vector.

#include <vector>

using namespace std;

int main(int argc, char *argv[]) {
    vector<vector<int>> grid(10, vector<int>(10, 10000));
    return 0;
}

When I define the same vector as a class member, it reports syntax error:

#include <vector>

using namespace std;

class Test {
public:
    vector<vector<int>> grid(10, vector<int>(10, 10000));
};

int main(int argc, char *argv[]) {
    vector<vector<int>> grid(10, vector<int>(10, 10000));
    return 0;
}

How can I define a class member of type vector<vector<int>> and initialize it with 10 vector<int>(10, 10000)? I tried to declare the variable and initialize it in the constructor, but the compiler reports C:\my_projects\cpp1\main.cpp(8): error C2064: term does not evaluate to a function taking 2 arguments.

#include <vector>

using namespace std;

class Test {
public:
    Test() {
        grid(10, vector<int>(10, 10000));
    }

public:
    vector<vector<int>> grid;
};

int main(int argc, char *argv[]) {
    vector<vector<int>> grid(10, vector<int>(10, 10000));
    return 0;
}
2 Answers

You can use braced initializer or equal-sign initializer for default member initializer (since C++11), which doesn't support parentheses initializer; as the error message said, it attempts to be interpreted as function.

E.g.

class Test {
public:
    vector<vector<int>> grid{10, vector<int>(10, 10000)};
};

or

class Test {
public:
    vector<vector<int>> grid = vector<vector<int>>(10, vector<int>(10, 10000));
};

Your constructor initializer is wrong. It should be (initializer(s) after ':'). Example (Live):

class Test {
public:
    Test() : grid(10, vector<int>(10, 10000))
    {
         // grid(10, vector<int>(10, 10000)); error: this is not initializer
         // grid = vector<vector<int>>(10, vector<int>(10, 10000)) - this is ok
    }

public:
    vector<vector<int>> grid;
};

and for in-class member initialization you can use curly braces '{' or '=' to avoid most vexing parse problem (Live):

class Test {
public:
    vector<vector<int>> grid{10, vector<int>(10, 10000)};
};
Related