CPP Friend function in C++

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.

Syntax:

class class_name
{
    ......  ....   ........
    friend return_type function_name(arguments);
    ......  ....   ........
}
  • Now, you can define friend function of that name and that function can access the private and protected data of that function.
  • No keywords in used in function definition of friend function.

Example:

#include <iostream>

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;
}
void main()
{
    Distance D;
    cout<<"Distace: "<<func(D);
    getch();
}

Output:

Distance: 5
  • Here, friend function func() is declared inside Distance class. So, the private data can be accessed from this function.
  • Though this example gives you what idea about the concept of friend function, this program doesn't give you idea about when friend function is helpful.


Share This Page to Download:

Share to Download

Share This Page on:

Question


Shaikh Uzair | 22-May-2016 10:48:16 am

PLzz Provide following Concepts 1. Pointer To Data Member 2. Pointer To Object 3. Pointer to Member Function 4. Operator Overloading (Unary & Binary with Friend function & without friend Function)


Ask Question

Classes and Objects