Lesson: C++ The tick function

What is the point of declaring the SetScreenPosition method outside of the class? I cant wrap my head around the need to do this since this feels far more cluttered and is not really saving any lines (in fact its adding more to the whole script),

thanks :slight_smile:

There are two main reasons we want to create setter and getter functions for a variable.

  1. 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).

  2. 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.

For me, I think Stephen Ulibarri is introducing this to us earlier probably for us to grasp the concept of header and implementation files later. I usually declared a class in a header file and defined it in a separate implementation file like this:

Header file, Character.hpp

Implementation file, Character.cpp

This is what was taught to me during my diploma days. (Not sure if I remember it correctly though…)
It is tedious for now.
But, it helps a lot later on when working with something like linked lists and big libraries.
For me, I love organizing things by separating each game’s mechanics/functionality into different headers/libraries.
I will know what to look for when refactoring later and it will be easier for readability and documentation later.
Correct me if I am wrong, I am still new to game design.

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms