Modifying member variable doesn't change its reference despite being pointed to
Nov 23, 2015 at 9:33am UTC
I am currently working Risk project and I'm having trouble changing the value of a specific Country instance within my Reinforcement Class. I have a pointer variable that points to its address so shouldn't it change when I modify the pointer variable? Could it be because of the copy constructor? I'm a c++ newbie so I'm not sure what the problem is.
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
//reinforcement.h
Reinforcement(vector<Country>& thelist);
//other
private :
Country * chosencountry;
vector<Country> listofcountries
void choosecountry();
void placearmy();
//reinforcement.cpp
Reinforcement (vector<Country> &thelist){
this ->listofcountries=thelist;
}
void choose country() {
//stuff
chosencountry=&listofcountries[index];
}
void placearmy() {
chosencountry.setArmy(n);//n obtained through calculations
//country.h
void setArmy(int n){army=n);
Country (Country &obj)//copy constructor
int getarmy() {return army;);
//main
vector<Country> countries
Reinforcement rein(countries)
rein.choosecountry();
rein.placearmy();
Nov 23, 2015 at 9:55am UTC
Each Reinforcement stores its own copy of the Country list.
Nov 23, 2015 at 1:45pm UTC
as Peter87 says, it happens at line 13.
because you assign the vector in your constructor you could change line 6 to be a reference and use an initializer list.
1 2 3 4 5 6 7 8
private :
vector<Country>& listofcountries;
public :
Reinforcement (vector<Country> &thelist)
listofcountries(thelist)
{
}
oh, and you dont need to prefix
this ->
when accessing members, that is implied.
Topic archived. No new replies allowed.