Customizable training materials to learn C++

Nano teach C++ found result for your search here:

C++ Friend Function

In C++ a function or an entire class may be declared to be a friend of another class or function. Friend function can also be used for function overloading.
Friend function declaration can appear anywhere in the class. But a good practice would be where the class ends. An ordinary function that is not the member function of a class has no privilege to access the private data members, but the friend function does have the capability to access any private data members. The declaration of the friend function is very simple. The keyword friend in the class prototype inside the class definition precedes it.

Example to Demonstrate working of friend Function

/* 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=10; //accessing private data from non-member function
    return d.meter; 
}

int main(){ Distance D;
    cout<<"Distace: "<<func(D);
    system("pause"); 
    return 0;
}
Program Output:
Distance: 10
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.
In C++, friend means to give permission to a class or function. The non-member function has to grant an access to update or access the class.
The advantage of encapsulation and data hiding is that a non-member function of the class cannot access a member data of that class. Care must be taken using friend function because it breaks the natural encapsulation, which is one of the advantages of object oriented programming. It is best used in the operator overloading.

No comments:

Post a Comment