Tuesday, September 30, 2014



A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class.

Even though the prototypes for friend functions appear in the class definition.

  •  friends are not member functions. 
  •  friend can be a function, function template, or member function, or a class or class template.

Program bellow is the example how to use Friend Function to do addition,Subtraction and find a Max Number between two number using C++ Programming.

explanation: User need to key in two number, x number and y number, and the program will do the calculation for addition and subtraction and also determine the highest number between x and y.

Sample Output:


Sample Source Code:

#include<iostream>
#include<string>

using namespace std;

class NUMBERS
{
      private:
              int x,y;
      public:

            NUMBERS():x(0),y(0){ }

            NUMBERS(NUMBERS &nm)
            {
             x=nm.x;
             y=nm.y;
            }

            void setinput(int a,int b)
            {

              x=a;
              y=b;

              }

              friend int addition(NUMBERS obj);
              friend int subtract(NUMBERS obj);
              friend int max_min(NUMBERS obj);

};

int addition(NUMBERS obj)
{
    return obj.x + obj.y;
}
int subtract(NUMBERS obj)
{
    return obj.x - obj.y;
}
int max_min(NUMBERS obj)
{
    if(obj.x > obj.y)
    {
    return obj.x;
    }
    else
    {
    return obj.y;
    }
};

int main()
{
    NUMBERS object;
    int a,b;

    cout<<"enter x : ";
    cin>>a;
    cout<<"enter y : ";
    cin>>b;

    object.setinput(a,b);

    addition(object);
    subtract(object);
    max_min(object);

    cout<<"\naddiction ="<<addition(object)<<endl;
    cout<<"substraction ="<<subtract(object)<<endl;
    cout<<"max_min ="<<max_min(object)<<endl;


           system("pause");
           return 0;
}

Tagged:

0 comments:

Post a Comment

Zul Ameen Blog © 2013 | Powered by Blogger | Blogger Template by DesignCart.org