Question

I've found a question sorta similar to this one, though put in a more complex way than I think I require (received a -2 for question score). Hopefully this will be easier to follow.

The general gist of things is the two classes involved are GUI and Player (I've had the same problem elsewhere with other classes, but if I can understand why this one isn't working, it should apply to the rest).

GUI includes "Player.h". The class Player has a public boolean variable 'hasBall'; When a 'Player' is passed into a function Pass() and the boolean value changed, it seems that it is only a temp object thus isn't updating the object being passed itself. See code below:

This works fine, boolean values for Plyr1A and Plyr2A (defined in Gui.h) are changed and preserved

Plyr1A.hasBall = false; 
Plyr2A.hasBall = true;

However boolean values for Plyr1A and Plyr2A remain the same with this.

Pass(Plyr1A,Plyr2A);  //Boolean values for Plyr1A and Plyr2A remain the same with this.

void GUI::Pass(Player passer, Player receiver) {
    passer.hasBall = false;
    receiver.hasBall = true;
}

If anyone could explain to me why this occurs I'd be rather thankful! If there is any extra information needed please let me know.

Cheers :)

Was it helpful?

Solution

Your function makes a copy of the arguments (they are passed by value), then changes the copy, not the "original" objects(in the body of the function).

You should change it to take pointers or references, for example:

//-------------------v---------------v   <---these are references
void GUI::Pass(Player& passer, Player& receiver) {

Of course, you should change the declaration, too.

OTHER TIPS

Use references to pass your objects.

Consider this function:

void someFunction (int j)
{
    j = 8;
}

And say we call it like this:

someFunction (3);

Are you thinking the assignment in someFunction somehow makes that 3 become an 8? Your expectation makes no sense. Without some kind of special arrangement, it cannot be that an assignment inside a function changes values in the caller.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top