#include <iostream>
usingnamespace std;
void func();
class A
{
private:
int z;
public:
int x;
int y;
friendvoid 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 ?
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 .
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.
#include <iostream>
usingnamespace std;
void func();
class A
{
private:
int z;
public:
int x;
int y;
friendvoid 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 (: