Empty vector problem

Hello,

Im having some problems implementing a vector of classes. Somehow when i fill the vector everything goes well. But at the moment I need to get something out of it its empty. The code goes like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class TestClass  {
    std::vector<TestClass2*> _tests;
public:
    //GET
    TestClass2* getTest    (int testNumber) {return _tests.at(testNumber);};
    std::vector<TestClass2*> getAllTests ()  {return _tests;};
    //ADD
    void addTest(TestClass2 test){
       TestClass2* tempTest = new TestClass2(tractor);
       _tests.push_back(tempTest);
    }  
}

int main(int argc, char **argv)
{
   TestClass test;
   TestClass2 test2;
   test.addTest(test2);
   test.getAllTests().size(); // Is empty
   test.getTest(0)->foo(); //Crash
}


I'm new to c++ so I'm probably just doing something stupid but I dont know what.
Last edited on
Neither do I.
I fixed/expanded your code so that it can be compiled and it gave no such error.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <vector>

int tractor = 5;

class TestClass2{
    int i;
public:
    TestClass2(int i=0) : i(i) {}
    void foo(){}
};

class TestClass  {
    std::vector<TestClass2*> _tests;
public:
    //GET
    TestClass2* getTest    (int testNumber) {return _tests.at(testNumber);};
    std::vector<TestClass2*> getAllTests ()  {return _tests;};//it would be better to return a reference here.
    //ADD
    void addTest(TestClass2 test){
       TestClass2* tempTest = new TestClass2(tractor);//what is tractor?
       _tests.push_back(tempTest);
    }  
};//you missed a column after class

int main(int argc, char **argv)
{
   TestClass test;
   TestClass2 test2;
   test.addTest(test2);
   int sz = test.getAllTests().size();
   test.getTest(0)->foo();
   return sz;//sz is 1 here
}
Topic archived. No new replies allowed.