473,385 Members | 1,925 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

friends in a class

i am just wondering what is the friend in a class , ive got a book
about c++ but it dosent explain deep enough . anyone care to make a
example with a few notes on what the friend can benifit from.
thanks

Oct 9 '05 #1
21 2067
ben
an****@gmail.com wrote:
i am just wondering what is the friend in a class , ive got a book
about c++ but it dosent explain deep enough . anyone care to make a
example with a few notes on what the friend can benifit from.
thanks


By declaring a friend you are granting access permission to the public,
protected and private part of the class. Usually, friendship can help
split your very large class into serveral dedicated on one job only.

An obvious example of the iterator in STL. In order for the iterators to
have special access to the standard containers' internal, the containers
must declare its iterators as friends.

A simpler example is an alarm_clock class, like the following:

class alarm_clock_maintainer;

class alarm_clock
{
private:
spring source;
gearbox gbox1;
gearbox gbox2;
// ... other internal stuff
public:
void run(void);
void set_alarm(time t);
void reset(time t);

friend class alarm_clock_maintainer;
};

class alarm_clock_maintainer;
{
private:
maintainers_toolbox tools;
complicated_stuff stuffs;
very_prof_knowledgebase knowledge;
// etc

public:
alarm_clock& inspect(alarm_clock& clock);
alarm_clock& replace_parts(alarm_clock& clock);
alarm_clock& oil(alarm_clock& clock);
// etc
};

Now notice by spliting the alarm_clock's interface into two classes you
immediately have simpler alarm_clock to work with, which does not come
with the burden of all the toolbox, complicated stuff and knowledge to
maintain a clock (because most user won't need those anyways.) But you
need to grand friendship to alarm_clock_maintainer, which needs access
to the spring and gearboxes and other stuffs in the alarm_clock, which
other user normally won't need to know.

Ben
Oct 9 '05 #2
thanks ben
so your always have to prototype the friend class , before you use it
and i am not sure about this

friend class alarm_clock_maintainer;
};

this was in the public section, so isnt it already public ,, did you
not mean to type it in the private section , so it can access the
public?

Oct 9 '05 #3
ye i am slightly confused with the above code ..would it be possible to
make a smaller version please as i tend to learn c++ from doing small
peices each time then understanding exactly what it does

Oct 9 '05 #4
hmm i dont know how to edit my messages so i have to type another ;/

so like i have
#include <iostream>
using namespace std;

class myclass
{
public: // all access granted for all the program
void function();

private // only varibles and functions within the class
};

void myclass::function()
{
cout<<"hello i am a newb"<<endl;
}

int main()
{
myclass myclasss;
myclasss.functions();
return 0;
}

can you some how fit something with friend in this code please :D

Oct 9 '05 #5
ok its this part which is taxing me

friend class alarm_clock_maintainer;
};
class alarm_clock_maintainer;

why do you make the same name of class as you do with the friend inside
a class..
wouldent this mean a class inside a class :o

Oct 9 '05 #6
Ian
an****@gmail.com wrote:
thanks ben
so your always have to prototype the friend class , before you use it
and i am not sure about this

friend class alarm_clock_maintainer;
};
It's not a prototype, it's a forward declaration. It tells the compiler
that there is a class alarm_clock_maintainer and that it is a friend of
the current class.
this was in the public section, so isnt it already public ,, did you
not mean to type it in the private section , so it can access the
public?

It doesn't matter where you put the friend declaration, just a matter of
style.

Ian
Oct 9 '05 #7
an****@gmail.com wrote:
ok its this part which is taxing me

friend class alarm_clock_maintainer;
};
class alarm_clock_maintainer;

why do you make the same name of class as you do with the friend inside
a class..
wouldent this mean a class inside a class :o


Firstly, read up about Usenet. This is not a forum.

Secondly, classes within classes are perfectly legal, but that's *not*
what's happening here.

From the original example:

This is called a forward declaration. It tells the compiler that a class
named "alarm_clock_maintainer" exists, but doesn't tell it anything
about the details of the class. Before you can use this type the proper
class definition must be visible, but for our "friend" declaration we're
not using any information other than the class name, so this is good enough.
class alarm_clock_maintainer;

This is the definition of a class that happens to have private stuff.
All the type names listed in "friend" declarations are allowed to access
our private stuff directly without using the public class interface we
provide.
The friend declaration can be in any part of the class definition, it
doesn't need to be in the public section. It always means the same
thing: the type named in the declaration is allowed to access our
private stuff.
class alarm_clock
{
private:
spring source;
gearbox gbox1;
gearbox gbox2;
// ... other internal stuff
public:
// ... other public stuff

friend class alarm_clock_maintainer;
};

Here's the actual definition of alarm_clock's friend. I think the rule
is that friends have to be defined in the same translation unit, but I
could be wrong about that.
Now, when you call "my_alarm_clock_maintainer.inspect(my_alarm_clock) "
the inspect() function is allowed to examine all of the private members
of alarm_clock, e.g. alarm_clock::gbox1. If alarm_clock didn't have the
friend declaration then this class wouldn't be allowed to do that.
class alarm_clock_maintainer;
{
private:
// ... internal stuff
public:
alarm_clock& inspect(alarm_clock& clock);
// ... other public stuff
};
Jacques.
Oct 9 '05 #8
so you create a class with no { };
if your making a friend

Oct 9 '05 #9
an****@gmail.com wrote:
so you create a class with no { };
if your making a friend


No you don't.

You make a forward declaration of the class to tell the compiler "later
on I will define a class with this name". This does not "create a class
with no {};". Sorry for being pedantic, but little details matter. :-)

class foo;

Then you tell the class with private stuff that he has a friend named foo.

class bar{
friend class foo;
int x;
...
};

Then you define foo as you normally would.

class foo{
void f(bar& b){ b.x = 3; }
};

Without the friend declaration in class bar, foo::f would not be legal
because it refers to a member name which is private in bar (bar::x).
Oct 9 '05 #10
#include <iostream>
using namespace std;

class class2;

class class1
{
public:
int v;

friend class class2; //so now class 1 can access private class2
varibles?
};

class class2
{
int varible;
};

int main()
{
class1 classs;
classs.varible = 5;
return 0;
}

i thought this would give access to varible for public use
i cant undertand this :(

Oct 9 '05 #11
an****@gmail.com wrote:
#include <iostream>
using namespace std;

class class2;

class class1
{
public:
int v;

friend class class2; //so now class 1 can access private class2
varibles?
No, now class2 is allowed to access *your* private members.
};

class class2
{
int varible;
};

int main()
{
class1 classs;
classs.varible = 5;
No, this is wrong. Friendship only applies within the scope of class2's
member functions.
return 0;
}

i thought this would give access to varible for public use
i cant undertand this :(

You're look at it from the wrong direction.

class B;

class A{
private:
int i;
public:
friend class B;
};

class B{
public:
void change_A(A& a){ a.i = 3; }
};

A must say "he's my friend, so he can access my private stuff" rather
than saying "I'm his friend, so I can access his private stuff".
Friendship is designed into the class that has the private stuff, not
tacked onto another class to bypass visibility constraints.

Jacques.

Oct 9 '05 #12
ben wrote:
an****@gmail.com wrote:
i am just wondering what is the friend in a class , ive got a book
about c++ but it dosent explain deep enough . anyone care to make a
example with a few notes on what the friend can benifit from.
thanks


By declaring a friend you are granting access permission to the public,
protected and private part of the class. Usually, friendship can help
split your very large class into serveral dedicated on one job only.


Or to put it in another (perhaps more memorable :)) way...

Only you and your friends can play with your private parts.

Oct 9 '05 #13
now jacques that makes sense to me now, cleary explained that the
friend class is the one that can take stuff from the private section of
the class you create the friend in
thank you

Oct 9 '05 #14
red floyd wrote:
Or to put it in another (perhaps more memorable :)) way...

Only you and your friends can play with your private parts.


Exactly. And you can't say "I'm that guy's friend"... He has to name you
as a friend in his definition.

Jacques.
Oct 9 '05 #15
class b; //something for the compiler

class pee
{
//private varibles of class pee;
int a;
int b;
int c;
int d;
friend class b; //creating the opening so b can use private varibles in
p
};
class bee
{
};

int main()
{
pee peee;
peee.a = 15; //i know i cant do this because a is private of class pee;

return 0; //so how the hell do i get assign something to a from
class bee
}

Oct 9 '05 #16
this is what i mean

class bee; //something for the compiler

class pee
{
//private varibles of class pee;
int a;
int b;
int c;
int d;
friend class bee; //so bee can use private varibles of pee;
};
class bee
{
public:
void function()
{
a = 1;
}
};

int main()
{
return 0;
}

Oct 9 '05 #17
an****@gmail.com wrote:
class b; //something for the compiler

class pee
{
//private varibles of class pee;
int a;
int b;
int c;
int d;
friend class b; //creating the opening so b can use private varibles in
p
};
class bee
This should also be "class b", to match your forward declaration.
{

Only class b can do the assignment. Create a member function like so:

public:
void assign(pee& p, int number){ p.a = number; }

};

int main()
{
pee peee;
peee.a = 15; //i know i cant do this because a is private of class pee;
b my_b;
my_b.assign(peee, 15);

return 0; //so how the hell do i get assign something to a from
class bee
}

Oct 9 '05 #18
an****@gmail.com wrote:
this is what i mean

class bee
{
public:
void function()
{
a = 1;
}
Not quite... You need a particular instance of the pee class to work on.
e.g.
void function(pee& p, int number){
p.a = number;
}
};

int main()
{
pee p;
bee b;
b.function(p, 3);
return 0;
}

Oct 9 '05 #19
void function(pee& p, int number)
{
p.a = number;
}

i am not sure what & is doing , is it saying its another name for pee
like when you make a object in main for a class

Oct 9 '05 #20
Ian
an****@gmail.com wrote:
void function(pee& p, int number)
{
p.a = number;
}

i am not sure what & is doing , is it saying its another name for pee
like when you make a object in main for a class

I think it's time for you to get a decent C++ book and look up references.

Ian
Oct 9 '05 #21
ben
an****@gmail.com wrote:
thanks ben
so your always have to prototype the friend class , before you use it
and i am not sure about this

friend class alarm_clock_maintainer;
};

this was in the public section, so isnt it already public ,, did you
not mean to type it in the private section , so it can access the
public?


Perhaps a simpler version can help: say we have two classes X and Y:

class X
{
private: int a;
// ...
};

class Y
{
public: void f(X& x);
};

void Y::f(X& x)
{
++x.a;
}
Now it just happens that Y::f needs to increment x.a to finish its job.
But since X::a is a private member, this is a access violation and hence
cannot compile. Why? Because X::a is meant not to be accessed
eleswhere--unless X specifically grant access to some party which may
have a special permission (friendship) to access X's private. So the
above code becomes:

class X
{
private: int a;
// ...

friend class Y;
};

class Y
{
public: void f(X& x);
};

void Y::f(X& x)
{
++x.a;
}

Note that now X explicitly grants Y the permission to access X::a (and
other private members.) But there is a problem you see: when the
compiler reads the line

friend class Y;

Y isn't declared yet. Now the compiler, not having any knowledge on Y
(yet), is confused by the friend statement and will emit an error saying
it doesn't know what Y is.

So we need to let the compiler know what Y is before the friend
statement. A simple way is to define Y before X:
class Y
{
public: void f(X& x);
};

class X
{
private: int a;
// ...

friend class Y;
};

void Y::f(X& x)
{
++x.a;
}

Immediately we face another problem here: when the compiler reads the line

public: void f(X& x);

it has no way to tell what X is in the same way it didn't know what Y
was in the previous example.

To remedy, we can forward declare Y to tell the compiler:
1. Y is a class; and
2. Y's definition will be available later in the program.

So here we have got the finial (and workable) version:

class Y; // foreward declaration, but not definition

class X
{
private: int a;
// ...

friend class Y; // OK, since Y is known to be a class
};

class Y
{
public: void f(X& x);
};

void Y::f(X& x)
{
++x.a;
}

Alternatively, we can foreward declare X:

class X; // foreward declaration, not definition

class Y
{
public: void f(X& x); // Ok, X is known to be a class
};

class X
{
private: int a;
// ...
};
void Y::f(X& x)
{
++x.a; // Ok, X::a is known to be an int
}

Ben
Oct 9 '05 #22

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

Similar topics

11
by: Sean Don | last post by:
Hello! Is it possible to make classes friends in Python? Or is it better to just stick to "Java style" .isThis, .getThat, .setThis style functions? I understand that classes are generally...
1
by: Gianni Mariani | last post by:
I have 2 distinct template classes which co-operate, hence are friends. However, I can't seem to figure out what syntax to use to make this work. What is the right(tm) way to write a friend...
5
by: Pete C. | last post by:
I'm trying to make a templated function a friend like this: class cls { ... friend cls func<> (const cls& a, const cls& b); }; template< template<class> class Op> cls func (const cls& a,...
3
by: fabio de francesco | last post by:
Hello, I have written this code that compiles without errors ( "..." stays for code that I don't post for the sake of brevity): // Person.h .... class Person { public:
11
by: Micha | last post by:
Hello there, I think I've run into some classic c++ pitfall and maybe some of you guys can help me out. For my project I will need to use matrices and vectors and so I decided to implement them...
6
by: (Pete Cresswell) | last post by:
I'm makeing a little DB to help manage high school class reunions. One feature I'm trying to implement is "Friends". e.g. Fred Smith is a friend of Joe Jones and Bill Anderson. We record...
3
by: shaun roe | last post by:
Hello, I am working in a framework with certain restrictions; in particular I have a 'data' class with getter and setter methods, and a some 'filling' classes which know how to insert the data to...
2
by: Dave Rudolf | last post by:
Hey all, So I have a template class whose only template parameter is a type that the class is to manage. It's actually an implementation of the common Singleton design pattern. The class looks...
11
by: t | last post by:
Lippman's C++ Primer, 4th ed., p575 says: Friendship is not inherited. Friends of the base class have no special access to members of its derived class. If a base class is granted friendship,...
1
by: Dan Smithers | last post by:
Can a make a private member function a friend? The code below suggests not. I am using g++ 4.2.3 I realise that I can make the whole CFriend class a friend, or make my friend function public but...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.