user18702020
user18702020

Reputation: 21

Friend Function can't access private member of private member

#include <iostream>

using namespace std;

class A {
    friend void print(B&);
    int number;
};

class B {
    friend void print(B&);
    A object;
};

void print(B& C) {
    cout << C.object.number;
};

This code won't compile. It gives me E0265 error (member A::number is inaccessible)

Upvotes: 2

Views: 139

Answers (2)

JeanLColombo
JeanLColombo

Reputation: 160

This is a forward declaration issue. Class A has a print function that takes a reference to a class B instance, but class B has not being defined yet. So the compiler doesn't understand and gives an error.

Try this:

#include <iostream>

using namespace std;

class B;

class A {
    friend void print(B&);
    int number;
};

class B {
    friend void print(B&);
    A object;
};

void print(B& C) {
    cout << C.object.number;
};

Upvotes: 1

GTA
GTA

Reputation: 253

the issue is that the class B is not declared. A forward declaration fix the compile error.

#include<iostream>

using namespace std;

class B;
class A {
    friend void print(B&);
    int number;
};

class B {
    friend void print(B&);
    A object;
};

void print(B& C) {
    cout << C.object.number;
};

int main(){
    return 0;
}

Upvotes: 5

Related Questions