Why doesn't updating pointer variable change the variable that it points to?

I've got a class called state
1
2
3
4
5
class State{
double x,y,z;
std::vector<double *> state = {&x,&y,&z};
void set(int id, double val){*state[id] = val;}
};


Most of the time the set function works fine, as it should. But sometimes it only updates the "state" vector, and not the variable itself, which is super strange since it's just a pointer. So say

1
2
3
4
5
6
7
8
9
10
11
12
13
14

int main(){
State s;
s.set(0,0); // works fine
fun1(&s);
}
void fun1(State * s){
s->set(1,10); // this sets y, ok
fun2(s);
}
void fun2(State * s){
s->set(2,20); // this only sets the state[2] and not the z
}


So yeah, super strange. I had a similar code before, but then it was more like

1
2
3
4
5
6
7
class State{
double state[3];
double * x = &state[0];
double * y = &state[1];
double * z = &state[2];
void set(int id, double val){state[id] = val;}
};


and that worked fine. What's going on?

Edit:

I've also tried now

1
2
3
4
5
class State{
double x,y,z;
double * state[3] = {&x,&y,&z};
void set(int id, int val){*state[id] = val;}
}


And this doesn't work either.


Edit2:

Ok, I figured it out. Actually my State class also had an assignment operator like

1
2
3
4
5
6
7
8
9
10
11
12
13
State{
double x,y,z;
double * state[3] = {&x,&y,&z};
void set(int id, double val){ *state[id] = val; }
State & operator=(const State & src) {for(int i = 0; i < 3; i++) *state[i] = *src.state[i]; }
}

void fun(State * s){
State s2;
s2 = *s; // this is ok
State s1 = *s; // this is not ok apparently
}


So yeah, apparently you can't use copy operator at initialization. Anybody knows the reason for that?
Last edited on
You need to implement the copy constructor as well.

1
2
s2 = *s; // calls the copy assignment operator
State s1 = *s; // calls the copy constructor, same as doing: State s1(*s) 
Last edited on
Yeah, super! Actually I've had a lot of problems pop up in the rest of my code, probably because of that as well. Good to know why. Cheers!
Topic archived. No new replies allowed.