forstack overflowizi
forstack overflowizi

Reputation: 424

friend member function can't access private member data

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

Answers (3)

Vlad from Moscow
Vlad from Moscow

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

Jarod42
Jarod42

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; }

Demo

Upvotes: 2

scohe001
scohe001

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

Related Questions