How to declare friendship-ness to all inherited class?

K

Kai Wu

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
 
M

Matt Bitten

--- Kai Wu said:
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;
}
};
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top