473,626 Members | 3,936 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

need for friend function

Stroustrup, in his book TC++PL 3rd Edition, in page 16, under the
section '1.8 Advice' has mentioned the following:
[2] [a] Don't use global data(use members)
[b] Don't use global functions
[c] Don't use public data members.
[d] Don't use friends, except to avoid [a] or [c].

Consider the following scenarios:

Scenario 1:
----------------
class Test
{
friend ostream & operator<<(ostr eam &os, const Test &ref);
}

Here the friend ostream &operator<<( ) can be avoided by providing a
Test::print_out put() function and expect the user to explicitly call
Test_obj.print_ output(os) for an object Test_obj of type Test.

Scenario 2:
----------------
class Test
{
friend Test operator+(const Test &arg1, const Test &arg2);
}

This friend function can be avoided as follows:

class Test
{
Test &operator+=(con st Test &ref);
}

Test operator+(const Test &arg1, const &arg2)
{
Test temp(arg1);
return temp += arg2;
}

Scenario 3:
----------------
Consider invert(m) for inverting a 'Matrix m' to the alternative
m.invert()
By providing Matrix::invert( ), here also the friend function can be
avoided.

I want to know if there are some guidelines and examples where the
need for using a friend function is unavoidable.

Kindly explain.

Thanks
V.Subramanian
Dec 4 '07 #1
19 2712
su************* *@yahoo.com wrote:
[..]
I want to know if there are some guidelines and examples where the
need for using a friend function is unavoidable.
Here is the thing: absence of evidence is not evidence of absence.
If I've never encountered in my whole life any guidelines and/or
examples where using a friend function is unavoidable, it does not
mean there isn't any. However, consider this: if there are better
ways of doing something, and you have no reason for *not* using one
of the better ways, then the "not so good" mechanism is avoidable.
Invert that, and you get this: if there are compelling reasons not
to use any of the ways to avoid something, then this something
becomes unavoidable. If for some reason you cannot grant access
to some private data to everybody (declare the data public or
protected), *and* you cannot make certain function a member of the
class containing the private data, then you are stuck with making
the function a friend. I know, it's not concrete, but that's the
essence, AFA I'm concerned.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Dec 4 '07 #2
On Dec 4, 3:56 pm, "subramanian10. ..@yahoo.com, India"
<subramanian10. ..@yahoo.comwro te:
Stroustrup, in his book TC++PL 3rd Edition, in page 16, under the
section '1.8 Advice' has mentioned the following:
[2] [a] Don't use global data(use members)
[b] Don't use global functions
[c] Don't use public data members.
[d] Don't use friends, except to avoid [a] or [c].

Consider the following scenarios:

Scenario 1:
----------------
class Test
{
friend ostream & operator<<(ostr eam &os, const Test &ref);

}

Here the friend ostream &operator<<( ) can be avoided by providing a
Test::print_out put() function and expect the user to explicitly call
Test_obj.print_ output(os) for an object Test_obj of type Test.

Scenario 2:
----------------
class Test
{
friend Test operator+(const Test &arg1, const Test &arg2);

}

This friend function can be avoided as follows:

class Test
{
Test &operator+=(con st Test &ref);

}

Test operator+(const Test &arg1, const &arg2)
{
Test temp(arg1);
return temp += arg2;

}

Scenario 3:
----------------
Consider invert(m) for inverting a 'Matrix m' to the alternative
m.invert()
By providing Matrix::invert( ), here also the friend function can be
avoided.

I want to know if there are some guidelines and examples where the
need for using a friend function is unavoidable.

Kindly explain.

class A;
class B;
class C

C foo(A a,B b){
//I need to access private members of A,B and C.
//I must be a friend of at least two of them.
};

regards,
FM.

Dec 4 '07 #3
On Dec 4, 2:23 pm, terminator <farid.mehr...@ gmail.comwrote:
On Dec 4, 3:56 pm, "subramanian10. ..@yahoo.com, India"

<subramanian10. ..@yahoo.comwro te:
Stroustrup, in his book TC++PL 3rd Edition, in page 16, under the
section '1.8 Advice' has mentioned the following:
[2] [a] Don't use global data(use members)
[b] Don't use global functions
[c] Don't use public data members.
[d] Don't use friends, except to avoid [a] or [c].
Consider the following scenarios:
Scenario 1:
----------------
class Test
{
friend ostream & operator<<(ostr eam &os, const Test &ref);
}
Here the friend ostream &operator<<( ) can be avoided by providing a
Test::print_out put() function and expect the user to explicitly call
Test_obj.print_ output(os) for an object Test_obj of type Test.
Scenario 2:
----------------
class Test
{
friend Test operator+(const Test &arg1, const Test &arg2);
}
This friend function can be avoided as follows:
class Test
{
Test &operator+=(con st Test &ref);
}
Test operator+(const Test &arg1, const &arg2)
{
Test temp(arg1);
return temp += arg2;
}
Scenario 3:
----------------
Consider invert(m) for inverting a 'Matrix m' to the alternative
m.invert()
By providing Matrix::invert( ), here also the friend function can be
avoided.
I want to know if there are some guidelines and examples where the
need for using a friend function is unavoidable.
Kindly explain.

class A;
class B;
class C

C foo(A a,B b){
//I need to access private members of A,B and C.
//I must be a friend of at least two of them.

};

regards,
FM.
Most of the time you can use public methods instead...
Dec 4 '07 #4
On Dec 4, 8:23 am, terminator <farid.mehr...@ gmail.comwrote:
On Dec 4, 3:56 pm, "subramanian10. ..@yahoo.com, India"

<subramanian10. ..@yahoo.comwro te:
Stroustrup, in his book TC++PL 3rd Edition, in page 16, under the
section '1.8 Advice' has mentioned the following:
[2] [a] Don't use global data(use members)
[b] Don't use global functions
[c] Don't use public data members.
[d] Don't use friends, except to avoid [a] or [c].
Consider the following scenarios:
Scenario 1:
----------------
class Test
{
friend ostream & operator<<(ostr eam &os, const Test &ref);
}
Here the friend ostream &operator<<( ) can be avoided by providing a
Test::print_out put() function and expect the user to explicitly call
Test_obj.print_ output(os) for an object Test_obj of type Test.
Scenario 2:
----------------
class Test
{
friend Test operator+(const Test &arg1, const Test &arg2);
}
This friend function can be avoided as follows:
class Test
{
Test &operator+=(con st Test &ref);
}
Test operator+(const Test &arg1, const &arg2)
{
Test temp(arg1);
return temp += arg2;
}
Scenario 3:
----------------
Consider invert(m) for inverting a 'Matrix m' to the alternative
m.invert()
By providing Matrix::invert( ), here also the friend function can be
avoided.
I want to know if there are some guidelines and examples where the
need for using a friend function is unavoidable.
Kindly explain.

class A;
class B;
class C

C foo(A a,B b){
//I need to access private members of A,B and C.
//I must be a friend of at least two of them.

};

regards,
FM.
Sorry term, I think that is a very bad example. you may give the OP
the idea that any constructor with an argument will have to be a
friend of the argument type, which is quite false.

A and B should have public accessors, which the constructor of C can
use. If for some reason A and B cannot provide accessors, than that is
the reason for making them friends to C. However, the example does not
illustrate that unknown reason for A and B not having accessors.
Dec 4 '07 #5
On Dec 4, 8:09 am, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
subramanian10.. .@yahoo.com wrote:
[..]
I want to know if there are some guidelines and examples where the
need for using a friend function is unavoidable.

Here is the thing: absence of evidence is not evidence of absence.
If I've never encountered in my whole life any guidelines and/or
examples where using a friend function is unavoidable, it does not
mean there isn't any. However, consider this: if there are better
ways of doing something, and you have no reason for *not* using one
of the better ways, then the "not so good" mechanism is avoidable.
Invert that, and you get this: if there are compelling reasons not
to use any of the ways to avoid something, then this something
becomes unavoidable. If for some reason you cannot grant access
to some private data to everybody (declare the data public or
protected), *and* you cannot make certain function a member of the
class containing the private data, then you are stuck with making
the function a friend. I know, it's not concrete, but that's the
essence, AFA I'm concerned.

My complaint about friendship is that its too coarse grained. I
almost never see the situation where one class actually needs to
access the private data members of another (and that's usually pretty
easy to design around, even if you just add some getters and
setters). What I have run into is the situation where two or more
classes need to share some interfaces within the group, but not with
classes outside that group.

While there are ways around that (notably making the semi-public
interfaces part of derived classes, although that brings other
problems, particularly the need to use a factory method), none of the
workarounds are all that clean (of course, neither is excessively
permissive friendship).
Dec 4 '07 #6
ro***********@y ahoo.com wrote:
[..]
My complaint about friendship is that its too coarse grained. I
almost never see the situation where one class actually needs to
access the private data members of another (and that's usually pretty
easy to design around, even if you just add some getters and
setters). What I have run into is the situation where two or more
classes need to share some interfaces within the group, but not with
classes outside that group.

While there are ways around that (notably making the semi-public
interfaces part of derived classes, although that brings other
problems, particularly the need to use a factory method), none of the
workarounds are all that clean (of course, neither is excessively
permissive friendship).
To provide the functionality where only members of the group have
access to each other's privates ("family"? :-)) you can define
a "shared" class which will be the friend of them all and though
which they will request the access. Kind of like this:

class A {
int a;
friend class P;
public:
void foo();
};

class B {
int b;
friend class P;
public:
void foo();
};

class P { // everything is private
friend class A;
friend class B;
static int &a(A& ai) { return ai.a; }
static int &b(B& bi) { return bi.b; }
};

void A::foo() {
B myb;
a = P::b(myb);
}

void B::foo() {
A mya;
b = P::a(mya);
}

int main() {
A a;
B b;
a.foo();
b.foo();
}

Note that 'A' is not a friend of 'B', nor 'B' is a friend of 'A'.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Dec 4 '07 #7
On Dec 4, 3:04 pm, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
robertwess...@y ahoo.com wrote:
[..]
My complaint about friendship is that its too coarse grained. I
almost never see the situation where one class actually needs to
access the private data members of another (and that's usually pretty
easy to design around, even if you just add some getters and
setters). What I have run into is the situation where two or more
classes need to share some interfaces within the group, but not with
classes outside that group.
While there are ways around that (notably making the semi-public
interfaces part of derived classes, although that brings other
problems, particularly the need to use a factory method), none of the
workarounds are all that clean (of course, neither is excessively
permissive friendship).

To provide the functionality where only members of the group have
access to each other's privates ("family"? :-)) you can define
a "shared" class which will be the friend of them all and though
which they will request the access. Kind of like this:

class A {
int a;
friend class P;
public:
void foo();
};

class B {
int b;
friend class P;
public:
void foo();
};

class P { // everything is private
friend class A;
friend class B;
static int &a(A& ai) { return ai.a; }
static int &b(B& bi) { return bi.b; }
};

void A::foo() {
B myb;
a = P::b(myb);
}

void B::foo() {
A mya;
b = P::a(mya);
}

int main() {
A a;
B b;
a.foo();
b.foo();
}

Note that 'A' is not a friend of 'B', nor 'B' is a friend of 'A'.

Yes, I've seen that pattern (more precisely with accessor classes for
each class in the family, rather than one big one for the whole
family), but it's far from pretty. At least with the derived class
approach you can call the functions with the normal type resolution
and syntax, although it's difficult to extend that to multiple
families (although that's only been an issue on a couple of occasions).
Dec 4 '07 #8
On Dec 5, 2:04 am, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
robertwess...@y ahoo.com wrote:
[..]
My complaint about friendship is that its too coarse grained. I
almost never see the situation where one class actually needs to
access the private data members of another (and that's usually pretty
easy to design around, even if you just add some getters and
setters). What I have run into is the situation where two or more
classes need to share some interfaces within the group, but not with
classes outside that group.
While there are ways around that (notably making the semi-public
interfaces part of derived classes, although that brings other
problems, particularly the need to use a factory method), none of the
workarounds are all that clean (of course, neither is excessively
permissive friendship).

To provide the functionality where only members of the group have
access to each other's privates ("family"? :-)) you can define
a "shared" class which will be the friend of them all and though
which they will request the access. Kind of like this:

class A {
int a;
friend class P;
public:
void foo();
};

class B {
int b;
friend class P;
public:
void foo();
};

class P { // everything is private
friend class A;
friend class B;
static int &a(A& ai) { return ai.a; }
static int &b(B& bi) { return bi.b; }
};
static functions accessing non-static member variables?
void A::foo() {
B myb;
a = P::b(myb);
}

void B::foo() {
A mya;
b = P::a(mya);
}

int main() {
A a;
B b;
a.foo();
b.foo();
}

Note that 'A' is not a friend of 'B', nor 'B' is a friend of 'A'.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Dec 5 '07 #9
On Dec 5, 8:18 am, Rahul <sam_...@yahoo. co.inwrote:
On Dec 5, 2:04 am, "Victor Bazarov" <v.Abaza...@com Acast.netwrote:
To provide the functionality where only members of the group have
access to each other's privates ("family"? :-)) you can define
a "shared" class which will be the friend of them all and though
which they will request the access. Kind of like this:
class A {
int a;
friend class P;
public:
void foo();
};
class B {
int b;
friend class P;
public:
void foo();
};
class P { // everything is private
friend class A;
friend class B;
static int &a(A& ai) { return ai.a; }
static int &b(B& bi) { return bi.b; }
};

static functions accessing non-static member variables?
Would that be a problem? Note that the static functions belong to
class P and the non-static members are of classes A and B.
Dec 5 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
17859
by: Nitin Bhardwaj | last post by:
Thanx in advance for the response... I wanna enquire ( as it is asked many a times in Interviews that i face as an Engg PostGraduate ) about the overloading capability of the C++ Language. Why can't the = (assignment) operator be overloaded as a friend function ? I work in VS 6.0 ( Win2000 ) as when i referred the MSDN documen'n it said the following :
2
10149
by: Christophe Barbe | last post by:
I posted a few days ago about the same problem but was not very clear. So here is my second take at it. Basically with GCC 3.3.2, I can't compile the example from the C++ FAQ Lite available online at http://www.parashift.com/c++-faq-lite/containers-and-templates.html#faq-34.15 Below are the two files that I compile with g++ foo.cpp -o foo or
10
2302
by: Piotr Wyderski | last post by:
Hello, is it possible to reuse a friend operator which is defined inside a class? I'd like to obtain the following behaviour: class integer { integer operator +(signed long int v) const {
15
6577
by: Samee Zahur | last post by:
Question: How do friend functions and static member functions differ in terms of functionality? I mean, neither necessarily needs an object of the class to be created before they are called and either has access only to static members of the class (ie. assuming no object of the class is in scope - neither by arguments recieved nor by local declarations). Any static member function like this: //accessing static member i static void...
1
1506
by: gw7rib | last post by:
Suppose I have a function, whose protoype is somewhat complicated, for example, with some #defines and typedefs, it looks like this: INT_PTR CALLBACK PropDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); and I'm not allowed to make it a member function <OTbecause it's a dialog box function </OT>. I want to make it a friend of my class, because it updates class
3
2790
by: Terry Olsen | last post by:
I'm trying to add a domain user to a local group using the code below: Dim LCL As New DirectoryEntry("WinNT://" + Environment.MachineName + ",computer") Dim DOM As New DirectoryEntry("WinNT://us.ups.com") Dim DOMUSR As DirectoryEntry = DOM.Children.Find("USERID", "user") Dim LCLGRP As DirectoryEntry = LCL.Children.Find("LOCAL_GROUP", "group")
15
2039
by: active | last post by:
Below is a small but complete program that appears to show you can't retrive a Palette from the clipboard. This is true whether the palette is placed on the clipboard by Photoshop or Photoshop or by the below program It lets you place a palette from a file or from a program on the clipboard and allows you to retrieve one from the clipboard. But you'll find the retrieved one is always "Nothing"
6
3161
by: WaterWalk | last post by:
I find friend declaration just very tricky. I tried the following examples on both MingW(gcc 3.4.2) and VC++ 2005. The results are surprising. Example1: namespace ns1 { class Test { friend void func()
9
2052
by: wo3kie | last post by:
#include <iostream> #include <map> #include <utility> // // Base // / | \ // Derived1 Derived2 \ // \ | / // Derived3
0
8266
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8199
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8705
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8365
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7196
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6125
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5574
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4198
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2626
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.