By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,958 Members | 1,179 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,958 IT Pros & Developers. It's quick & easy.

friendship with dependencies

P: n/a
Is there a way to do anything like the following:

class A
{
friend void B::foo();

...
};

class B
{
void foo();
...
A my_a;
};

This is very much simplified, but basically B depends upon A so that A
must be defined first, yet I want to make one member function of B a
friend of A.

Thanks,
Mark
Oct 12 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Mark P wrote:

Is there a way to do anything like the following:

class A
{
friend void B::foo();
...
};

class B
{
void foo();
...
A my_a;
};

This is very much simplified, but basically B depends upon A so that A
must be defined first, yet I want to make one member function of B a
friend of A.
Two ways come to mind, neither of which is wholly satisfactory. First,
make B, rather than B::foo(), a friend of A. This makes the friendship
broader than required, but does not require you to define B before
defining A.

Second, you could change B::my_a to either a pointer or a reference to
A, instead of an actual A. That would permit you to forward-declare A,
then define B, then define A. A could in that definition grant
friendship to B::foo, as you require.

Best regards,

Tom

Oct 12 '06 #2

P: n/a

Mark P wrote:
Is there a way to do anything like the following:

class A
{
friend void B::foo();

...
};

class B
{
void foo();
...
A my_a;
};

This is very much simplified, but basically B depends upon A so that A
must be defined first, yet I want to make one member function of B a
friend of A.

Thanks,
Mark
What for? B::foo() has access to my_a regardless of their respective
access specifiers with respect to B. In the case where class A has some
private part you want B::foo() to have access to, it makes more sense
to modify A's interface.
Friendifying B or B::foo() is more likely to create new issues rather
than providing a maintainable fix.
For example, friends are not inherited.

Also, the member must be constructed first but that is entirely under
the control of the Container's creation process (unless, of course, you
forfeit the right to do so).

example:

class A
{
int a;
public:
A() : a(0) { } // def ctor, guarantees a valid int
A(int n) : a(n) { }
void setA(int n) { a = n; }
};

class B
{
A a;
public:
B() : a() { } // or whatever...B() : a(-1) { }
B(int n) : a(n) { }
void foo() { a.setA(99); }
};

Its now impossible to generate an instance of A or B with uninitialized
members.

Oct 13 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.