Thursday, 26 December 2013

C++ program to demonstrate the working of friend function

#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<<"Distace: "<<func(D);
    return 0;
}
*************************************
Output
Distance: 5
//////////////////////////////////////////////////////////////////////
C++ Programming friend Function and friend Classes

One of the important concept of OOP is data hiding, i.e., a nonmember function cannot access an object's private or protected data. But, sometimes this restriction may force programmer to write long and complex codes. So, there is mechanism built in C++ programming to access private or protected data from non-member function which is  friend function and friend class.

friend Function in C++

If a function is defined as a friend function then, the private and protected data of class can be accessed from that function. The complier knows a given function is a friend function by its keyword friend. The declaration of friend function should be made inside the body of class (can be anywhere inside class either in private or public section) starting with keyword friend.
class class_name
{
    ......  ....   ........
    friend return_type function_name(argument/s);
    ......  ....   ........
}

No comments:

Post a Comment