There are two main reasons we want to create setter and getter functions for a variable.
-
We don’t want to give direct access to the variable from outside of its class or limit access. For example, leaving screenPos as private would allow us to only give outside code a getter and not a setter (or the other way around).
-
There’s extra processing we need to do in order to set or get the value contained in the variable properly. With this particular case, we’re allowing SetScreenPos to self-contain code for calculating the actual screen position so we don’t have to type it out over and over again.
I also think you’re confusing the difference between a declaration and definition.
This is the function declaration that’s in the class:
void setScreenPos(int winWidth, int winHeight);
.
And this its definition:
void Character::setScreenPos(int winWidth, int winHeight)
{
screenPos = {(float)winWidth / 2.0f - 4.0f * (0.5f * (float)texture.width / 6.0f),
(float)winHeight / 2.0f - 4.0f * (0.5f * (float)texture.height)
};
}
Which, as far as the compiler is concerned, is also contained inside of the class.