469,923 Members | 1,573 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,923 developers. It's quick & easy.

How to declare friendship-ness to all inherited class?

Hello,

struct S{
friend class B;
private:
int i;
};

class B{
B(){}
virtual ~B(){}
};

class D : public B{
};

it turns out that although for D, its parent class B is a friend of S, D is
not a friend to S, therefore
it is allowed to manipulate private member i of S within D. Should i declare
friend class all one by one in S
or is there a succinct way of expressing that all the inherited class of B
should be friend of S?

br,Kai
Jul 23 '05 #1
2 1404
Sorry to bother, read the FAQ, it looks it is not possible by rules.

"Kai Wu" <ka******@nokia.com> wrote in message
news:uA****************@news2.nokia.com...
Hello,

struct S{
friend class B;
private:
int i;
};

class B{
B(){}
virtual ~B(){}
};

class D : public B{
};

it turns out that although for D, its parent class B is a friend of S, D is not a friend to S, therefore
it is allowed to manipulate private member i of S within D. Should i declare friend class all one by one in S
or is there a succinct way of expressing that all the inherited class of B
should be friend of S?

br,Kai

Jul 23 '05 #2
--- Kai Wu wrote:
Should i declare friend class all one by one in S
or is there a succinct way of expressing that all
the inherited class of B should be friend of S?


The second idea is impossbile. The first is generally
unacceptable, since it does not provide for future
derived classes.

So try it a different way. Give B a new member function
that returns a reference to the appropriate member of S.
Declare this new member function "protected". Then all
derived classes of B, even those you don't anticipate,
can access this data member of S through the function.

struct S {
friend class B;

private:
int i;
};
class B {
B(){}
virtual ~B(){}

protected:
int & geti(struct S & ss) {
return ss.i;
}
const int & geti(const struct S & ss) {
return ss.i;
}
};

Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

7 posts views Thread by Erik | last post: by
2 posts views Thread by Lance Geeck | last post: by
1 post views Thread by marfi95 | last post: by
5 posts views Thread by Mike Gleason jr Couturier | last post: by
4 posts views Thread by werasm | last post: by
reply views Thread by Hanshika Sathey | last post: by
6 posts views Thread by Hicham Mouline | last post: by
reply views Thread by Waqarahmed | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.