friend function definition - type issues

Why doesn't the following compile and give a type error for the friend function? What would be a way to fix this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class B;

class A{
public:
friend void B::bla();
};

class B{
void bla(){};
};

int main{
return 0;
}


Thanks.
With friend it is the class whose private members you want to access who needs to declare friendship.

You can't just bypass the private access by declaring yourself to be a friend, the one with the private members has to let you in.

So I think you might be trying to do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class B;

class A{
public:
// B must make A a friend to allow it to call void bla()
};

class B{
	friend class A; // Now class A can call B::bla()
void bla(){};
};

int main() // need parentheses here
{
return 0;
}
Last edited on
Galik,

Thank you, but no.

I understand it isn't obvious from the code I posted and that I should have made it more transparent, but I want B to access A.

More importantly, I do not want to allow all of B to access A, but only the specific function bla(). It is in this case that the compiler complains about the underdefined type. If I define the entire class B as a friend of A, it has no problems.
Oh, sorry.

Then I think you will need to declare class B completely before class A.
Ah, here we go, wherein bla actually does something:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class A;

class B{
public: void bla(A*);
};

class A{
int i;
public:
friend void B::bla(A*);
};

void B::bla(A*){p->i = 2;};


Compiles and works.

Thank you!
Topic archived. No new replies allowed.