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