Peter Chen Peter Chen - 1 year ago 89
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{
bool test;

void anotherSetTest();
void setTest();
void Globle_scope_function(A a){

test = false;
void A::setTest(bool foo){
test = foo;
void A::anotherSetTest(){
int main(){
A a;
cout<<a.getTest()<<endl;//It suppose to output true, but why does it output false.
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download