Scope confusion: How can the BullCowCount struct access and increment MyCurrentTry, a private member variable inside a different class?

Apologies if this is a dumb question, or doubtless reveals my lack of understanding on how the scope of these things work. I thought the entire point of private class variables was that they can only be accessed and altered by public methods of the same class, hence all our roundabout stuff with getters etc.

Suddenly we build a totally separate object, a struct, and it can just directly access and increment the private “MyCurrentTry” variable from the FBullCowGame class, with no issues? Totally lost on that and trying to re-evaluate my understanding of the point and rules of ‘private’ now.

1 Like

… nvm, in Rubber Duck fashion I think I’ve wrapped my head around it now:

The BullCowCount struct isn’t accessing anything itself, it’s just the return-type of the SubmitGuess method, which itself is, of course, a public member of FBullCowGame and thus able to access and modify the private members of that class.

2 Likes

Hey @Paraprax and dear Community,

the definiton of the struct BullCowCount is outside and above of the class in the file FBullCowGame.h.

#pragma once
#include <string>

using FString = std::string;
using int32 = int;

// All integers, initialized to zero.
struct BullCowCount
{
	int32 Bulls = 0;
	int32 Cows = 0;
};

class FBullCowGame {
public:
	FBullCowGame(); // constructor

	int32 GetMaxTries() const;
	int32 GetCurrentTry() const;
	bool IsGameWon() const;

	void Reset(); // TODO make a more rich return value.
	bool CheckGuessValidity(FString); // TODO make a more rich return value.
	BullCowCount SubmitGuess(FString);


// ^^ Please try and ignore this and focus on the interface above ^^
private:
	// see constructor for initialisation
	int32 MyCurrentTry;
	int32 MyMaxTries;
	FString MyHiddenWord;
};

I’ve tried to access the private-variables within the class from the struct - it’s not accessible.

Kind regards
Kevin

Privacy & Terms