Timothy Kelly
Timothy Kelly

Reputation: 19

Friend Function can't see private member

I've tried to figure this out for an hour now and I've gotten nowhere.

I have a class with a friend function and private members but I am getting a compiler error telling me that I cannot access a private member using that friend function.

line 36 error: 'family* family::famPtr' is private

The friend prototype is as follows within the class body

friend void output(family *famPtr);

The private members are as such:

private:
    string husband;
    string wife;
    string son;
    string daughter1;
    string daughter2;
    family *famPtr;

And this is the function call itself within the main function for a family object Simpson.

output(Simpson.famPtr);

I'm not sure where I'm messing up here, it seems relatively simple and my textbook is getting me nowhere and none of the things I've found on here have led me in the right direction.

Upvotes: 0

Views: 196

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

You may not call the function the following way

output(Simpson.famPtr);

because relative to the scope where the function is called data member Simpson.famPtr is private.

It is within the function where you could use expression Simpson.famPtr.

That is it is the function itself that is the friend. It is not the scope where the function is called is the class friend.

If the class would contain a public accessor like for example

family * get_family() const;

then you can call the function like

output(Simpson.get_family() );

Upvotes: 3

Glenn Teitelbaum
Glenn Teitelbaum

Reputation: 10343

Making a function a friend allows it to access private members. It does not allow access in all calls to the function

output(Simpson.famPtr);

Here the access to famPtr is not made by output

If you change output to

output(family & outer)
{
   old_output(outer.famPtr);
}

Then the access to private member famPtr is contained within the friend function

Upvotes: 0

R Sahu
R Sahu

Reputation: 206727

There seems to be a design flaw in your program.

Making a function that takes a family* as input a friend of the class Simpson does not make sense at all.

The function does not deal with Simpson, It deals with family. How will making that function a friend of Simpson help?

It's difficult for me to suggest a solution since it's not clear to me why you wanted the friend-ship in the first place.

Upvotes: 2

Related Questions