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


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

}

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
Thanks. I got it now.
Topic archived. No new replies allowed.