Tuesday, 16 June 2015

FRIEND FUNCTION : DEMONSTRATION


Friend function is used to access the data members of class where it has been declared.It is not "actually" part of class but still using the object of class as parameter it has the authority to access the data members.


#include <iostream>
using namespace std;
class Distance
{
   private:
       int meter;
   public:
       Distance(): meter(0){ }
       friend int func(Distance);  //friend function
};
int func(Distance d)            //function definition
{
   d.meter=5;         //accessing private data from non-member function
   return d.meter;
}
int main()
{
   Distance D;
   cout<<"Distance: "<<func(D);
   return 0;
}


No comments:

Post a Comment