I was reading about friendship in c++(i thought i actually understood it), but when I go to the source code to try it out within some classes, i just don't manage to get it going. I wish to be able to understand WHY it isn't working.
I've already done some research within this website and some others, and i actually found some code that worked, but i really can't see how the logic i'm trying to implement is different from the it:https://www.geeksforgeeks.org/friend-class-function-cpp/
struct B;
struct A{
A(int _a): a(_a){}
friend void B::showA(A&);
private:
int a;
};
struct B{
void showA(A&);
};
void B::showA(A& _param){
cout << _param.a;
}
I expect the function void B::showA(A&) to be able to access the private member "a" of class A, but when i try to compile my code it produces these errors:
friendshipninheritance.cpp(10): error C2027: use of undefined type 'B'
friendshipninheritance.cpp(5): note: see declaration of 'B'
friendshipninheritance.cpp(21): error C2248: 'A::a': cannot access private member declared in class 'A'
friendshipninheritance.cpp(12): note: see declaration of 'A::a'
friendshipninheritance.cpp(7): note: see declaration of 'A'
As a rule of a thumb, you should solve compiler errors from top. Usually, one error can spawn more errors, and it's not different in this case.
Your friend
declaration was ignored, because compiler doesn't yet know what B
is and whether or not it has any function called showA
. This lead to all further errors.
You can change the order of declarations to make it work:
struct A;
struct B{
void showA(A&);
};
struct A{
A(int _a): a(_a){}
friend void B::showA(A&);
private:
int a;
};
void B::showA(A& _param){
cout << _param.a;
}