Philosophical reason behind the concept of friend function

M

Madhav

Hi all,
I am a newbie in c++. I want to know what is the
philosophical reason behind the existence of friend functions. I
thought giving access to private data to a function which is not a
member of the class is a violation of encapsulation.

Thanks,
Madhav.
 
A

Aleksander Beluga

Madhav said:
Hi all,
I am a newbie in c++. I want to know what is the
philosophical reason behind the existence of friend functions. I
thought giving access to private data to a function which is not a
member of the class is a violation of encapsulation.

Thanks,
Madhav.

Unfortunately, we're not living in an ideal world. That means that
sometimes (like when building singleton holder or some generic
framework) it's OK to access one's private properties. And, yeah,
sometimes (hey, I said SOMETIMES, don't kill me!) it is even appropriate
to use goto :eek:)
 
G

GB

Madhav said:
Hi all,
I am a newbie in c++. I want to know what is the
philosophical reason behind the existence of friend functions. I
thought giving access to private data to a function which is not a
member of the class is a violation of encapsulation.

Thanks,
Madhav.

It is only giving access to *arbitrary* functions (e.g., by making data
public) that is a violation of encapsulation. Having the class identify
a *specific* function for access is not a violation of encapsulation,
since the class is giving that access. The function becomes part of the
encapsulation along with the member functions. That said, it should be
rare that non-members need such access.

Gregg
 
B

benben

Madhav said:
Hi all,
I am a newbie in c++. I want to know what is the
philosophical reason behind the existence of friend functions. I
thought giving access to private data to a function which is not a
member of the class is a violation of encapsulation.

Thanks,
Madhav.

The philosophical reason: to extend encapsulation boundary over that
defined by the class.

Ask yourself what is being encapsulated from whom :)

Regards,
Ben
 
J

Jerry Coffin

@i39g2000cwa.googlegroups.com>, (e-mail address removed)
says...
Hi all,
I am a newbie in c++. I want to know what is the
philosophical reason behind the existence of friend functions. I
thought giving access to private data to a function which is not a
member of the class is a violation of encapsulation.

The reason is pretty simple: sometimes functions that are
part of the interface to a class can't actually be member
functions. When this happens, the non-member function is
normally made a friend of the class.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top