Reputation: 424
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?
Upvotes: 0
Views: 88
Reputation: 311126
You have to define the class A before the class X for example like
class X;
class A {
public:
void func(X x1);
};
class X {
int foo;
public:
friend void A::func(X x1);
};
void A::func(X x1) { x1.foo = 999; }
Or instead of the forward declaration
class X;
you can use an elaborated type specifier like
class A {
public:
void func(class X x1);
};
class X {
int foo;
public:
friend void A::func(X x1);
};
void A::func(X x1) { x1.foo = 999; }
Upvotes: 0
Reputation: 218278
You have to split correctly declaration and definition, as you have circular dependency:
class X;
class A {
public:
void func(X x1);
};
class X {
int foo;
public:
friend void A::func(X x1);
};
void A::func(X x1) { x1.foo = 999; }
Upvotes: 2
Reputation: 15446
There's another error that you're ignoring. Namely:
error: 'A' has not been declared
You'll need to declare the class A
with the function before you can reference it in X
as a friend. However, the function takes an X
, so you also need to declare X
first!
It should look like:
class X;
class A {
public:
void func(X x1);
};
class X {
int foo;
public:
friend void A::func(X x1);
};
void A::func(X x1) { x1.foo = 999; }
Upvotes: 1