How does including Reset() in the constructor work?

I would like to know how Reset(); modifies the values of MyMaxTries and MyCurrentTry when called in the constructor, because as far as I know, void functions cannot modify previously initialized variables as they basically don’t return anything

FBullCowGame::FBullCowGame()
{
	Reset();
}

void FBullCowGame::Reset()
{
	constexpr int MAX_TRIES = 8;
	MyMaxTries = MAX_TRIES;
	MyCurrentTry = 1;
	return;
}

I do not know what the exact code is, but MyMaxTries and MyCurrency must be defined somewhere, where they can be accessed by the Reset() function, therefore allowing the call to Reset() result in the change in what those variables hold.

Basically, you could say they are global variables, which can then be accessed by any other function.

e.g. If the code was like this:

int MyMaxTries = 0;
int MyCurrentTry = 0;

void FBullCowGame::Reset()
{
	constexpr int MAX_TRIES = 8;
	MyMaxTries = MAX_TRIES;
	MyCurrentTry = 1;
	return;
}

Then MyMaxTries and MyCurrentTry would be totally accessible by Reset().

I’d have to see the code to give a complete answer. I’m not on the Unity course, so no idea what the actual code is, but the reason why it can change those variables, is due to where and how those variables were defined.

A function does not need to return a value or use pass by reference (&) to change things.

Hopefully, that was of some help. I’m not very good with terminology; that goes over my head :slight_smile:

Ah ha, read up on “scope” in programming.

Scope in C#
https://msdn.microsoft.com/en-us/library/ms973875.aspx
on MSDN (Microsoft)
https://msdn.microsoft.com/en-us/library/ms973875.aspx

Lots of info out there, just search around :slight_smile:

EDIT:

constexpr int MAX_TRIES = 8;

Being a constant, never changing, that need not go in Reset(). Best to stick that where MyMaxTries and MyCurrentTry are defined. Of course, not knowing exactly how/where MyMaxTries and MyCurrentTry are defined, I could be wrong.

The point is, " constexpr int MAX_TRIES = 8;" needs only to be executed once, when the program starts.

Thank you for replying,
in the example you’ve shown the Reset function is a void function, I agree with you that it can access MyMaxTries and MyCurrentTry as if they were global variables, but as far as I understand, void functions create copies from the variables in their body unless these variables were called by reference, here is the example you’ve shown:

int MyMaxTries = 0;
int MyCurrentTry = 0;

void FBullCowGame::Reset()
{
	constexpr int MAX_TRIES = 8;
	MyMaxTries = MAX_TRIES;
	MyCurrentTry = 1;
	return;
}

calling the Reset function shouldn’t affect the values of MyCurrentTry and MyMaxTries because they weren’t called by reference in the function Reset

here is the full project:
image
image

PS: Excuse my little knowledge, I only started learning C++ a few months ago.

Privacy & Terms