C++ varible not retaining value

Associate
Joined
16 Nov 2011
Posts
1,000
Location
127.0.0.1
I have a class which has a vector list of the same type of class, I also have a method that calls a function and recalls it for each in the vector.

Code:
void Body::add()
{
	obj.doSomething();
	for each(Body bo in sat)
	{
		bo.add();
	}
}

(I have changed some method and variable names as I can't post my actual code)

The class which is called has a integer variable in the header file and a method which increments the integer.

Code:
private:
	int an;

Code:
void here::doSomething()
{
	an++;
}

"an" is set in the constructor to 0. You would expect the first time add() is called that all instances of "an" would be 1, then 2 etc. However, only the 1st instance is 1, then 2, the rest do not retain the value.

If I cout in another method I get
Code:
1
0
0
0
2
0
0
0
3
0
0
0
etc..

I have no idea what is causing this to happen, it just doesn't make any sense.
 
Last edited:
Associate
OP
Joined
16 Nov 2011
Posts
1,000
Location
127.0.0.1
Try declaring an as static. Each instance of Body has it's own variable of "an" currently

I want each instance to have it's own variable of "an" ("an" is in the class "here" not "Body"), I have a method in Body which calls an update method for all instances of "here", in which "cout << an << endl;" is called. This and the add method of Body (in which "an" is incremented), which is called for each instance of "here" in which "an" is a member variable is called at the same time.

So it's like:
add() on the root object of type "Body" which calls add() on all the other instances of "Body"
add() calls doSomething() on it's member variable of type "here"
dosomething() therefor is called for each instance of "here"
sosomething() increments "an"

Body::update() on root object of type "Body" which calls Body::update() on all other instances
Body::update() calls here::update() on it's member variable of type "here"
here::update {cout << an << endl;}
 
Last edited:
Associate
OP
Joined
16 Nov 2011
Posts
1,000
Location
127.0.0.1
Sounds like your child Body instances are getting copied, and you're only incrementing the counter in a temporary copy.

Add an explicit copy constructor to Body and stick a breakpoint in it.

Thanks, that solved it, it seems that the for each loop is not part of the standard C++. The for each loops that I was using was creating a temporary copy. Using a standard for loop works fine.
 
Back
Top Bottom