Peter Chen Peter Chen - 3 months ago 8
C++ Question

Object value can not be changed

I am a new c++ programmer, and have learned some java before. I am do my assignment. And I just could not get my heard around this problem.

class A{
private:
bool test;

public:
void anotherSetTest();
void setTest();
A();
};
void Globle_scope_function(A a){
a.setTest(true);
}

A::A(){
test = false;
}
void A::setTest(bool foo){
test = foo;
}
void A::anotherSetTest(){
Globle_scope_function(*this);
}
int main(){
A a;
a.anotherSetTest();
cout<<a.getTest()<<endl;//It suppose to output true, but why does it output false.
system("pause");
return 0;
}


When I use visual studio to debug, it tells me that the object has gone out of scope. How do I solve it... :-< . Edit it to MWV.

Answer

Calling Globle_scoop_function(*this); takes a deep copy of *this to the function parameter a. It's that object that goes out of scope at the end of Globle_scoop_function. The object *this remains unmodified.

One remedy would be to change the prototype to void Globle_scoop_function(A& a){. Note the & which denotes a reference. You then modify the a in main() through that reference.

The fact that all the various instances of A in your code are all called a only adds to the confusion.