I was just learning C++ friend classes. As it says on books and tuts, a friend class can access all the members (private and protected) too. But does not happen to be that in my case.
I know there's this stupid error that i cannot see. Please help me find it :D
My code:
#include <iostream>
using namespace std;
class A;
class B {
private:
int num;
public:
B(int n=0):num(n){}
friend int add(A, B);
friend int mul(A, B);
friend int sub(A, B);
void showthis(A);
friend class A;
};
class A{
private:
int num;
public:
A(int n=0):num(n){}
friend int add(A, B);
friend int mul(A, B);
friend int sub(A, B);
};
int add(A a, B b){
return a.num+b.num;
}
int sub(A a, B b){
return a.num-b.num;
}
int mul(A a, B b){
return a.num*b.num;
}
void B::showthis(A a){
cout<<a.num<<endl;
}
int main(){
A a(3);
B b(6);
cout<<add(a,b)<<endl;
cout<<mul(a,b)<<endl;
cout<<sub(a,b)<<endl;
b.showthis(a);
}
The error:
q17.cpp: In member function ‘void B::showthis(A)’:
q17.cpp:20:6: error: ‘int A::num’ is private
int num;
^
q17.cpp:43:10: error: within this context
cout<<a.num<<endl;
You declared neither B::showthis(A)
nor class B
as class A
's friend.
You could add either
friend B::showthis(A);
or
friend class B;
into class A.