Vector of Classes

I'm trying to learn to use classes in a vector. So far I understand vectors and basic data types, but not sure about vectors and classes.

I have thus far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <vector>
using namespace std;

class Test
{
      int num;
   public:
      void setNum(int i) { num = i; }
      void printNum() { cout << num << endl;
};

int main()
{
   vector<Test*> vTestor;
   vector<Test*>::iterator vitTest;
   return 0;
}

I wasn't sure how you would do push_back/pop_back with that, but I know to print it I would do vTestor->printNum();, but that is about as clear as it was for me.
A vector of Tests is vector<Test>, not vector<Test*>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>
using namespace std;

class Test
{
      int num;
   public:
      Test(int i) : num(i) {}
      void printNum() const { cout << num << '\n';}
};

int main()
{
   vector<Test> vTestor;

   Test t1(7);
   vTestor.push_back(t1);
   vTestor[0].printNum();
}
Oh, all the sample code I found and tried to understand had vector<Entity*> vec; vec[0]->attack(); so I didn't know if I had to do pointers or not.
I would use a vector of pointers if I was going to use polymorphism.
Okay, thanks for clearing that up.
Topic archived. No new replies allowed.