Why can't I declare a vector inside a C++ class ?

May 19, 2018 at 1:14pm

Why can't I declare a dynamic array (vector) inside a C++ class ? In the following snippet, the static array 's' seems to work fine but vector 't' creates error during compilation . (I compiled using GNU G++ compiler).


1
2
3
4
5
6
7
8
9
10
11
  

class node
{
    int s[5];  // Seems to work fine

    vector<int> t(5);  // Creates error

}

May 19, 2018 at 2:24pm
You can. The question is how to initialize the member correctly:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <vector>

struct Node
{
  int s[5];
  std::vector<int> t;
  Node() : t(5) {} // constructor with member initializer list
};

int main()
{
  Node foo;
  std::cout << foo.t.size();
}

5
Last edited on May 19, 2018 at 2:25pm
May 19, 2018 at 5:51pm
Thanks. I got it now.
Topic archived. No new replies allowed.