'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)
Solution 1:[1]
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;
}
Solution 2:[2]
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;
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GTA |
| Solution 2 | JeanLColombo |
