friend classes and functions

J

Jess

Hello,

I am trying to define a friend function for my class as follows:

#include<iostream>

using namespace std;

class B;

class A{
friend void B::g(const A&);
//friend class B;
private:
int x;
public:
A(int a):x(a){}
};

class B:public A{
public:
B(int a):A(a){}
void g(const A& a){cout << a.x << endl;}
};

However, this failed with compiler error saying A::x is private and
member B::g is declared before type B is defined. This is surprising
because I've given forward declaration for B. I also declared B::g as
a friend, and so I think it should be able to access A::x. What is
going wrong here?

I then tried to replace friend void B::g(const A&) with friend class B
and then it worked. However, I'd only like B's g method to access A's
private part, not the whole B class. Is there a solution for my
problem?

Thanks,
Jess
 
J

John Harrison

Jess said:
Hello,

I am trying to define a friend function for my class as follows:

#include<iostream>

using namespace std;

class B;

class A{
friend void B::g(const A&);
//friend class B;
private:
int x;
public:
A(int a):x(a){}
};

class B:public A{
public:
B(int a):A(a){}
void g(const A& a){cout << a.x << endl;}
};

However, this failed with compiler error saying A::x is private and
member B::g is declared before type B is defined. This is surprising
because I've given forward declaration for B. I also declared B::g as
a friend, and so I think it should be able to access A::x. What is
going wrong here?

You cannot make a member function a friend based on only a forward
declaration of the class.
I then tried to replace friend void B::g(const A&) with friend class B
and then it worked. However, I'd only like B's g method to access A's
private part, not the whole B class. Is there a solution for my
problem?

No, but what is the problem exactly? Friendship of individual member
functions is fairly pointless. Since you are writing both classes,
whether they are friends of each other of not is only of concern to you.
It makes no difference at all to the users of your class, it's only an
implementation detail for your class. So just declare B to be a friend of A.

Thanks,
Jess

john
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top