Can someone please help me figure out why this is happening i cants see anything wrong




Would you mind pasting it? Can’t see anything inherently wrong with it. Also you should be consistent with your name re: “Reset” not “reset”

May be too late…
But in the FBullCowGame.cpp file, you declared the MyCurrentTry and MyMaxTries as int again. Since they were already declared in the *.h file, you should only assign values to them in the FBullCowGame.cpp file.

So inside the void FBullCowGame::reset() function in the FBullCowGame.cpp file, the correct code would be
constexpr int MAX_TRIES = 8;
MyMaxTries = MAX_TRIES;
MyCurrentTry = 1;
return;

3 Likes

scalagator is 100% right.

To explain a bit more as to why, it has to do completely with the scope of the variables. And as your example shows, C++ is able to differentiate between same named variables in different scopes. When a conflict of these same named variables occurs, C++ will use the variable with the smallest scope by default.

To show another example of this, consider the following block of code:

#include <iostream>
int Number = 0;

void Initialize() {
    constexpr BIG_NUMBER = 12;
    int Number = BIG_NUMBER;
}

int GetNumber() { return Number; }

void main() {
    Initialize();
    std::cout << GetNumber() << std::endl;
 }

When you run this code, you’ll get the same issue that you’re having with your own code. Despite the fact that you’re initializing a variable named Number to be 12, the Number that is received from GetNumber() will still be 0. This is because at the time of initilization, a new Number variable is created that lives only within te Initialize() method. Once it’s done, the local variable with 12 in it is gone. This leaves only the Number that is set to 0.

Scalagator already showed the fix for this. I just wanted to flesh out more as to the why.

5 Likes

Ah, yes… I had quite the same issue just yesterday where for some reason I didn’t notice how the lector removed the “int” in front of “MyMaxTries = MAX_TRIES;” and “MyCurrentTry = 1;” when copying from the privates in .h and moving it to the constructor in .cpp.

After revising the lesson, I did notice where he did it but it still confused me, as he didn’t really mention or explain himself removing the "int"s.

Maybe he did explain it in a prior video and I just forgot, might be the case.

I compared my code to the code in the lesson’s materials and only the part where I didn’t remove "int"s differed. After removing them it worked again.

I find @scalagator’s and @binksayres’s responses helpful and will definitely try finding out more about it to really understand and not make the same mistake again.


EDIT: I found another great explanation on the same problem in another thread just here.

PS! My apologies for bumping a thread after the last reply was over a year ago! Quite new to these forums! On the other hand, hoping this helps other people with the same case.

Privacy & Terms