Created a private const variable but it can still be changed?

i created MyMaxTries as a const variable so when i set it in the constructor i assume it shouldnt be able to change.(This is just for learning not for practical code) but if i run the code MyMaxTries will = 5 instead of 2...also the same thing happens if i instead set MyMaxTries=5 in the GetMaxTries Method. It will still equal whatever was set in the get method rather then stay const.

Also if i set a value to MyMaxTries in the constructor as a const and then set it just as a normal int in GetMaxTries. It equals whatever is in the GetMaxTries method instead of the constructor. I thought if i set it as a const it will not change?

If i use a function to call the get method will MyMaxTries change to whatever is in that get method then change back to the const after exiting that function?

1
2
3
4
5
6
7
8
9
10
11
12

class FBullCowGame {

public:
	FBullCowGame();
	int GetMaxTries();

private:
	int MyCurrentTry;
	const int MyMaxTries = 2;

};




1
2
3
4
5
6
7
8
9

int FBullCowGame::GetMaxTries() { 
	return MyMaxTries; 
}

FBullCowGame::FBullCowGame()
{
	int MyMaxTries = 5;
}

Last edited on
1
2
3
4
5
6
7
FBullCowGame::FBullCowGame()
{
    // This creates it's own local variable and sets it to 5.
    //int MyMaxTries = 5;

    MyMaxTries = 5;   // This is what you mean to do
}


Although you can set a non-static constant in a constructor like this:
1
2
3
4
FBullCowGame::FBullCowGame(int max_tries)
    : MyMaxTries(max_tries)
{
}

After that, it can't be changed.
Last edited on
ahh i see, whats why when i type in MyMaxTries = 5; theres an error. So i would add const or int infront of it thinking its still talking about that class varible but if i am understanding correctly adding int infront of it creates a new local variable just with the same name?
if i am understanding correctly adding int infront of it creates a new local variable just with the same name?

Exactly. We say that the new variable "shadows" the other one.
Topic archived. No new replies allowed.