0

New to c++, I'm trying to make a simple start screen for a video game. I want the start screen to scroll in from the bottom of the screen. In order to do this, I have some member variables that are accessed in a function called Update. The problem I am having is that I initialize scrollStart in a constructor with non-zero values. However, when Update is called, I print out the y-value of scrollStart and it is 0. There is only one other member function in this class that doesn't touch scrollStart so I have no Idea why it is getting reset to zero. Does anyone more familiar with c++ have any ideas why this would be happening?

My header file likes something like this (irrelevant things removed):

class StartScreen : public GameEntity 
{
private:
    Vector2 scrollStart;

public:
    void Update();

}; 

My cpp file looks something like this:

StartScreen::StartScreen()
{
    ...

    Vector2 scrollStart = Vector2(SCREEN_WIDTH*0.5f, SCREEN_HEIGHT);
    printf("scrollStart Y: %f\n", scrollStart.y);   // prints 868 as it should
}

StartScreen::Update()
{
    printf("scrollStart Y: %f\n", scrollStart.y);  // prints 0
}
bitwitch
  • 467
  • 1
  • 5
  • 15
  • 3
    isn't that because you're using a local copy in your constructor and not the member variable...? think if you just remove the Vector2 from the constructor, it should work – Omid CompSCI Jul 01 '18 at 23:23
  • oh I did not understand that, but now that you say that it is so clear. I must remove the Vector2 before the variable name in the constructor, correct? – bitwitch Jul 01 '18 at 23:26
  • Yes, because that is creating a local variable that will only have that value within the constructor scope. You are not touching the actual member variable. – Omid CompSCI Jul 01 '18 at 23:26
  • Thank you, I have been staring at this for awhile. Another set of eyes can catch it so quickly. – bitwitch Jul 01 '18 at 23:28
  • 1
    You can also just have your own habit of using the keyword this and use it within any function within the class, so you know for sure you are referencing the member. variables. For instance in your constructor could do this->scrollStart = ... – Omid CompSCI Jul 01 '18 at 23:29
  • @bitwitch _"I have been staring at this for awhile."_ Pro Tip: Inspecting your code with the debugger works way better than just _staring_ at it. – πάντα ῥεῖ Jul 01 '18 at 23:40
  • or just use `m_scrollStart` so that you can tell, immediately, that it's a member variable (field), without having to use `this->` craziness all over the place. – 3Dave Jul 01 '18 at 23:47
  • Closed as duplicate, but to be fair the problem with debugging questions is usually that the same flawed assumptions that cause the confusion also make it hard to find the existing SO question. – MSalters Jul 02 '18 at 07:50

0 Answers0