Home > other >  Friend Function can't access private member of private member
Friend Function can't access private member of private member

Time:04-05

#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)

CodePudding user response:

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

CodePudding user response:

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;
};
  •  Tags:  
  • c
  • Related