I try to access a private member data of class X, with a friend function, which itself is a member function of class A.
Here's the code:
class X {
int foo;
public:
friend void A::func(X x1);
};
class A {
public:
void func(X x1) { x1.foo = 999; }
};
This won't compile for the reason:
Error C2248 'X::foo': cannot access private member declared in class 'X'
I tried changing the order, declaring A before X, but it didn't help..
What's causing this?
A::func()
is not declared. But pls pls don't write such thing in production code all people will hate you. If it's to understand what friend is doing it's okay... but you alost never needs that... The most pratical thing I saw is when you need to implementoperator<<
andoperator>>
. Other cases are most probably bad code designfunc()
is modifying a copy of whateverX
object is passed to it. The originalX
object is not modified. If you want that, pass it by reference instead:void func(X &x1)