Vectors and Classes

This is more like a general query than a question, but basically I was wondering whether it was possible to have a vector as a member of a class that stored objects of another class. For Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Class1
{
public:
     //stuff
private:
vector<Class2>myvector(5);
};

class Class2
{
    //stuff
};

int main()
{
Class1 object1;
Class2 object2; 

object1.myvector.push_back(object2);

return 0;
}


Would code similar to this work? Thanks.
Last edited on
Almost. I got it to work like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <vector>

class Class2
{
};

class Class1
{
    public:
        std::vector<Class2> myvector;
};

int main ( )
{
    Class1 object1;
    Class2 object2; 

    object1.myvector.push_back ( object2 );
}


Class2 has to be declared before Class1 for Class1 to use it, and myvector has to be public for you to use push_back on it. You also can't initialize myvector's size like that.
Last edited on
Ah. Thank you very much. One more thing then, how would I go about initializing the size of the vector?
You could use the constructor, or take advantage of the fact that Class2 doesn't have an implicit constructor taking an integer:
1
2
3
4
5
6
7
8
9
10
class C2 {};

class C1 {
    public:
        C1() : _vec1(5) {}

    private:
        std::vector<C2> _vec1;
        std::vector<C2> _vec2 {5};
};


EDIT:
If C2 DID have a constructor taking a single integer, you could still use the second syntax option by specifying the constructor is explicit:
1
2
3
4
class C2 {
    public:
        explicit C2(int) {}
};
Last edited on
That makes sense. Thanks for your help.
Topic archived. No new replies allowed.