c++methodsgettersetterreturn-by-reference

“Setter” method not changing a property, but a test method outputs "test"? (Resubmitted with minimal reproducable example)


Player::Player() {
    target = new NPC();
}

NPC Player::getTarget() {
    return *target;
}

This is the method that gets the memory address of the current NPC.

NPC::NPC() {
    relationship = -35.0;
}

float NPC::getRelationship() {
    return relationship;
}

bool NPC::setRelationship(float r) {
    relationship = r;
    return false;
}

These are the getter and setter functions.

I am using a player class and passing it as argument p to an onTrigger() method:

float rel = p->getTarget().getRelationship();

This is the "getter" being called

cout << p->getTarget().setRelationship(rel - 10.0);

This is the "setter" being called.

I tried to create a test method that simply outputs "test" and I called it in place of the "setter" method. It worked. So the problem must be in the definition of the setter...but it looks perfect :(


Solution

  • This method

    NPC Player::getTarget() {
        return *target;
    }
    

    creates a temporary object of the type NPC. So changing this temporary object does not influence on the object pointed to by target.

    If you want to change the original object then you have to return it by reference as for example

    NPC & Player::getTarget() {
        return *target;
    }