Passing a vector to a pointer help...

Ok so i pretty much got everything working, i just looked up a little help but i did the rest myself so at this point i have a question:

I need to do this in my game but i wanted a clear workspace to test it out so i made a new file.

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
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Player
{
    public:
        void Game();
        Player(vector<int> GETNUMBERS);
        ~Player();

    private:
        vector<int> *number = new vector<int>;
        vector<int> getNumbers;
};


Player::Player(vector<int> GETNUMBERS): getNumbers(GETNUMBERS)
{}


Player::~Player()
{
    delete number;
}


void Player::Game()
{
    number = &getNumbers;

    getNumbers.push_back(45);

    cout << number->at(0) << endl;
}


int main ()
{
    vector<int> temp;

    temp.push_back(0);

    Player p(temp);
    p.Game();
}


Now the variable in main is supposed to be temporary but when i output its 0 even though i pushed it back, why is that? Do i need to pass the pointer to the new vector in the parameters as well?
Last edited on
From what I can see, you are accessing the first number of the vector.
From your program, your vector now contains the following:
0 45

When you did getNumbers.push_back(45);, you actually added 45 to the end of the vector. Therefore, when you accessed element 0 of the variable, you are accessing the "0" that was input when the game started.

This is because the variable number is a pointer to the vector getNumbers, so when you edit getNumbers you also affect number, because they are actually the same thing.
but i thought temp was supposed to just initialize it? I didnt want to push back a number i just wanted to initialize it. i mean i could do getNumbers.clear(); but is there a way to just initialize it?
Last edited on
std::vector has a default constructor that initializes it to an empty vector. When you define it on line 42 you're not passing any argument, therefore calling the default constructor.
Topic archived. No new replies allowed.