Class objects in a vector

So I'm trying to store class objects in a vector:

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;

class Finish{
    int a, b;

public:

    int getA(){return a;}
    int getB(){return b;}

    Finish (int h, int j);
};


class Start{

    int num, jar;

std::vector<Finish> var;

public:

    Start (int,int);

///HERE
    void add(Finish k){
        Finish*test;
        test->getA();
        test->getB();
        var.push_back(*test);

    }
};

Start::Start (int c, int d){
    num = c;
    jar = d;
}

Finish::Finish (int h, int j)
    : a(h), b(j)
{}

int main(){

    Start bam (1,2);
    Finish boom(3,6);

    bam.add(boom);//<--- trying to store 'boom'

return 0;
}


1. Am I storing it correctly?
2. How would I access the stored data, say, if I wanted to compare it to other stored data or COUT it?
1. Am I storing it correctly?

No. You should simply do:

1
2
3
    void add(Finish k){
        var.push_back(k);
    }


2. How would I access the stored data, say, if I wanted to compare it to other stored data or COUT it?

"Stored data" being the std::vector<Finish>? You could make the vector public, or provide a getter for it:

1
2
3
4
std::vector<Finish> Start::getVar() const
{
    return var;
}


Accessing elements in a vector can be done with vector::operator[] or vector::at(), as in:

1
2
var[0] = Finish(1, 2);
var.at(0) = Finish(1, 2);


Edit: like I said, if you want to be able to modify the vector without hassle, make it public. Otherwise your getter will be a bit uglier:

1
2
3
4
5
6
7
8
std::vector<Finish> & Start::getVar()
{
    return var;
}

// now you can do...

bam.getVar().at(0) = Finish(1, 2);
Last edited on
Topic archived. No new replies allowed.