How two classes having the same Friend in C++ with example



A non – member function may have friendship with one or more classes. When a function has declared to have friendship with more than one class, the friend classes should have forward declaration. It implies that it needs to access the private members of both classes.

Example:
#include<iostream.h>
#include<conio.h>
class test
               {
                              int a;
                              public:
                              void get();
                              friend void display (test t, result s);
               };
class result
               {
                              int b;
                              public:
                              void put();
                              friend void display (test t, result s);
};
void test :: get()
{
               cin>>a;
}
void result :: put()
{
               cin>>b;
}
void display (test t, result s)
{
               cout<<t.a<<s.b;
}
void main()
{
clrscr();
               test k;
               result l;
               k.get();
               l.put();
               display(k, l);
               getch();
}

No comments:

Post a Comment