0

While creating a vector of defined size for further use in class, is it neccessary that the parameter for constructors of data members should be written in the initializer list of my class' constructor?

Why does

class MyHashMap {
public:
    vector<int> vec;
    MyHashMap():vec(1000001) {
        fill(vec.begin(), vec.begin() + 1000000, -1);
    }

works but,

class MyHashMap {
public:
    vector<int> vec(1000001);
    MyHashMap() {
        fill(vec.begin(), vec.begin() + 1000000, -1);
    }

does not work and gives an error like

Line 4: Char 22: error: expected parameter declarator
    vector<int> vec (1000001);
                     ^

If the same implementation is done using arrays,

class MyHashMap {
public:
    int data[1000001];
    MyHashMap() {
        fill(data, data + 1000000, -1);
    }

there is no issue.

I'm still a beginner at c++ if someone could help me that'd be awesome. Thanks

1 Answers1

0

You can't use parenthesis to pass parameters to a class member's constructor directly in its declaration inline, like you are trying to. You need to either:

  • use the parent class's member initialization list:
class MyHashMap {
public:
    vector<int> vec;
    MyHashMap() : vec(1000001, -1) {}
  • in C++11 and later, you can either use an initializer:
class MyHashMap {
public:
    vector<int> vec = vector<int>(1000001, -1);
    MyHashMap() = default;
  • or, you can use curly braces instead of parenthesis:
class MyHashMap {
public:
    vector<int> vec{1000001, -1};
    MyHashMap() = default;

Note, however, that in this last case, because std::vector has a constructor that takes a std::initializer_list as input, this syntax will actually create the vector using just 2 elements whose values are 1000001 and -1, it will not call the 2-param constructor to create the vector with 1000001 elements of value -1.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • @Scheff good catch, I keep forgetting about that. I have updated my answer – Remy Lebeau Mar 08 '21 at 08:12
  • "You can't use parenthesis to pass parameters to a class member's constructor in its declaration, like you are trying to." I'm not sure if I follow. In my post why does the **second code snippet**, the one having **`vector vec (1000001);`** doesn't work but the the final code snippet, the one with simple **array implementation `int data[1000001];`** works. I might be missing something obvious here, sorry for the trouble. – Prasanjeet Keshri Mar 08 '21 at 08:14
  • 1
    @PrasanjeetKeshri a plain C style array is just setting aside a chunk of fixed memory, it does not have a constructor. A vector does. You can't use parenthesis to call a constructor on a class member declaration, there is simply no syntax that allows that. – Remy Lebeau Mar 08 '21 at 08:15
  • Got it! Thanks a lot! – Prasanjeet Keshri Mar 08 '21 at 08:21