Reputation: 931
I've been doing an exercise for my programming course and the particular one I'm on now is about friend functions/methods/classes. The problem I'm having is that my friend function doesn't seem to be doing it's job; I'm getting "[variable name] is private within this context" errors around my code where I'm trying to access the variables that the friend function should have access to.
Here is the class definition in the header file (I cut out unnecessary stuff to save space).
class Statistics {
private: // The personal data.
PersonalData person;
public:
Statistics();
Statistics(float weightKG, float heightM, char gender);
Statistics(PersonalData person);
virtual ~Statistics();
...
friend bool equalFunctionFriend(Statistics statOne, Statistics statTwo);
friend string trueOrFalseFriend(bool value);
};
Here is the method where the errors are appearing.
bool equalFuntionFriend(Statistics statOne, Statistics statTwo)
{
// Check the height.
if (statOne.person.heightM != statTwo.person.heightM)
return false;
// Check the weight.
if (statOne.person.weightKG != statTwo.person.weightKG)
return false;
// Check the gender.
if (statOne.person.gender != statTwo.person.gender)
return false;
// If the function hasn't returned false til now then all is well.
return true;
}
So, my question is: What am I doing wrong?
EDIT: Problem has been solved by Angew. Seems it was just a typo... Very silly me!
Upvotes: 3
Views: 12363
Reputation: 110768
I'm guessing that heightM
, weightKG
and gender
are private to your PersonalData
class and this is why you're getting the error. Just because your functions are friends of Statistics
, doesn't mean they have access to the internals of the members of Statistics
. They only have access to the internals of Statistics
. In fact, Statistics
itself doesn't even have access to the internals of PersonalData
, so its friends certainly don't.
There are a few ways around this. You could make the members of PersonalData
public - but that's not a great idea because you will decrease encapsulation. You could make your functions also friends of PersonalData
- you might end up with a strange graph of friendships (like Facebook for C++ classes!). Or you could give PersonalData
some public interface that allows others to peek at its private data.
As @Angew pointed out in the comments, your function is named equalFuntionFriend
when the friend of Statistics
is named equalFunctionFriend
- you have a missing letter. That would also cause this problem.
Upvotes: 2