Search code examples
c++classgetset

Access variable via get-Method not working outside class


My problem is, that if I print the Energy value of a field within the set-method of the specific field, it'll be printed, but if I try to print it right after exiting the set-method (code line 2 or 3) it always has the value of zero.

With the set-method void Field::_dEnergy(double dEnergy) I want to assign a value to dEnergy of vvoField[][].

this->_vvoField()[uiY][uiX]._dEnergy(dCurrentEnergy);
std::cout << this->_vvoField()[uiY][uiX].dEnergy;
std::cout << "Energy: " << this->_vvoField()[uiY][uiX]._dEnergy();

My get-/set-methods look like this:

void Field::_dEnergy(double dEnergy)       { this->dEnergy = dEnergy; std::cout << this->dEnergy; };
double Field::_dEnergy()                   { return this->dEnergy; };

(For testing purposes I've set everything to public. Both get and set and the actual variable dEnergy within Field.)

Do I make anything wrong with the Brackets to specify the field or what's my problem here? If I print the energy of every field, none is set different than zero, so I guess the get is always giving 0.


Solution

  • The problem is in your _vvoFields() function.

    You are returning a temporary variable, (this is, a copy), instead of the internal variable.

    In order to return the internal variable, modify the function declaration to:

    std::vector<std::vector<Field> >& _vvoFields()

    Note the & after the return type.

    With this change, you are returning a reference to the internal variable, so any modification to it will update the internal value (since both are the same).

    This is different to the original definition, where you where returning a copy of the internal value, this is, a completely different instance.