panJames
asked on
Friend classes and methods
Hello experts!
To declare method of class A a friend of class B this method needs to be declared above declaration of class B.
To declare entire class A a friend of class B class A does not need to be declared above declaration of class B.
Why does compiler works this way, what logic is behind it?
To declare method of class A a friend of class B this method needs to be declared above declaration of class B.
To declare entire class A a friend of class B class A does not need to be declared above declaration of class B.
Why does compiler works this way, what logic is behind it?
#include <iostream>
using namespace std;
class X;
class Y {
public:
void print(X& x);
};
class X {
int a, b;
friend void Y::print(X& x);
public:
X() : a(1), b(2) { }
};
void Y::print(X& x) {
cout << "a is " << x.a << endl;
cout << "b is " << x.b << endl;
}
int main() {
X xobj;
Y yobj;
yobj.print(xobj);
}
#include <iostream>
using namespace std;
class X {
int a, b;
friend class F;
public:
X() : a(1), b(2) { }
};
class F {
public:
void print(X& x) {
cout << "a is " << x.a << endl;
cout << "b is " << x.b << endl;
}
};
int main() {
X xobj;
F fobj;
fobj.print(xobj);
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.