Friend Function - Use Cases

Use Cases

This approach may be used when a function needs to access private data in objects from two different classes. This may be accomplished in two similar ways

  • a function of global or namespace scope may be declared as friend of both classes
  • a member function of one class may be declared as friend of another one.
#include using namespace std; class B; // Forward declaration of class B in order for example to compile. class A { private: int a; public: A { a = 0; } void show(A& x, B& y); friend void ::show(A& x, B& y); // declaration of global friend }; class B { private: int b; public: B { b = 6; } friend void ::show(A& x, B& y); // declaration of global friend friend void A::show(A& x, B& y); // declaration of friend from other class }; // Definition of a member function of A; this member is a friend of B void A::show(A& x, B& y) { cout << "Show via function member of A" << endl; cout << "A::a = " << x.a << endl; cout << "B::b = " << y.b << endl; } // Friend for A and B, definition of global function void show(A& x, B& y) { cout << "Show via global function" << endl; cout << "A::a = " << x.a << endl; cout << "B::b = " << y.b << endl; } int main { A a; B b; show(a,b); a.show(a,b); }

Read more about this topic:  Friend Function

Famous quotes containing the word cases:

    And in cases where profound conviction has been wrought, the eloquent man is he who is no beautiful speaker, but who is inwardly drunk with a certain belief. It agitates and tears him, and perhaps almost bereaves him of the power of articulation.
    Ralph Waldo Emerson (1803–1882)

    Lovers’ quarrels are not generally about money. Divorce cases generally are.
    Mason Cooley (b. 1927)