Explain use of friend function in C++ with examples?
In this chapter of C++ interview questions, we will learn:
what is friend function in c++ with example?
use of friend function in c++
What is friend function in C++?
A friend function of a class is defined outside class but it can access all private and protected members of the class.
A friend function in c++ can be of two types:
method of another class.
It is not a member function and can't get 'this' pointer.
Need or use of friend function in C++
If a function required to built with have access of private members of a class, this type of scenario friend function in c++ is required.
Mostly this type of situation arises in operator overloading.
Example of friend function in C++
Lets see an example that use friend function in C++:
using namespace std;
friend void plength(Square S); // friend function
void slength(double sd); //slength() member function of Square class
void Square::slength(double sd)
void plength(Square S) //plength() is friend of Square
cout<<"Length of Square"<<" "<<S.side;
plength(S); //friend function for print length
Length of Square 13.0
Would you like to see your article here on tutorialsinhand.
program by tutorialsinhand.com
About the Author
Page Views :
Published Date :