Wednesday, March 28, 2018

Write a C++ program to illustrate friend function.


AIM: Write a C++ program to illustrate friend function.
THEORY:
 In object-oriented programming, a friend function, that is a "friend" of a given class, is a function that is given the same access as methods to private and protected data[1]
A friend function is declared by the class that is granting access, so friend functions are part of the class interface, like methods. Friend functions allow alternative syntax to use objects, for instance f(x) instead of x.f(), or g(x,y) instead of x.g(y). Friend functions have the same implications on encapsulation as methods.
A similar concept is that of friend class.
This approach may be used in friendly function 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.

SOURCE CODE:
#include<iostream>
using namespace std;
class first;
class second{
            int s;
            public:
            void get_value(){
                        cout<<"\n enter a number:";
                        cin>>s;
            }         
            friend void sum(second,first);
};
class first{
            int f;
            public:
            void get_value(){
                        cout<<"\n enter a number:";
                        cin>>f;
                        }         
                        friend void sum(second,first);
};
void sum(second d,first t){
            cout<<"\n sum of two numbers:"<<t.f+d.s;
}
int main(){
            first a;
            second b;
            a.get_value();
            b.get_value();
            sum(b,a);
}

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home