Can class B inherit a friend function from class A ?

Hi folks,

Something is not clear to me with the following code :


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
using namespace std;


void func();

class A
{
private:
	int z;
public:
	int x;
	int y;
	friend void func();
};

class B : public A
{

};

void func()  {
	A a ;
	a.z = 1;
	B b;
	b.z = 2;
	cout << " 123 " << endl;
}


int main ()
{
	func();
	return 0;
}


How come it is possible for func , to change the private values of an object of class B ?

Thanks ,
Davi
Last edited on
i don't know that a function could be friends with another class. as far as i know, only a class can be a friends with another class not the function
friends relations are not heritable. Do something like this:
1
2
3
4
class B : public A
{
   friend void func();
};
closed account (1vRz3TCk)
Friendship is not inherited.

See: http://www.parashift.com/c++-faq-lite/friends.html#faq-14.4
All I know that when I do not use the friend declaration , I can't access the "z" parameter of A , and of B , and please pay attention that B inherits from A , so from what Eclipse compiler (g++) says , there is nothing wrong with that .

Syuf , that's my point : even when I do not write
1
2
3
4
class B : public A
{
   friend void func();
};


and just
class B : public A {};
then func() can access the "z" parameter of both A and B .
And so what the question is about?
closed account (1vRz3TCk)
I think what you are seeing is that z is a part of A that is a part of B so func() can still access it. If you put extra private members in B, func() is not given access to them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
using namespace std;


void func();

class A
{
private:
	int z;
public:
	int x;
	int y;
	friend void func();
};

class B : public A
{
private:
    int zz;
};

void func()  {
	A a ;
	a.z = 1;
	B b;
	b.zz = 2;  // no access 
	cout << b.zz << endl; // no access 
}


int main ()
{
	func();
	return 0;
}
I got it , you can access the inherited fields that B got from A , but you cannot access the private fields of B that B didn't inherit from A . cool ,thanks (:
Topic archived. No new replies allowed.