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:
-
global function,
-
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++:
#include<iostream>
using namespace std;
class Square
{
double side;
public:
friend void plength(Square S); // friend function
void slength(double sd); //slength() member function of Square class
};
void Square::slength(double sd)
{
side=sd;
}
void plength(Square S) //plength() is friend of Square
{
cout<<"Length of Square"<<" "<<S.side;
cout<<endl;
}
int main()
{
Square S;
S.slength(13.0);
plength(S); //friend function for print length
return 0;
}
OUTPUT
Length of Square 13.0
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Page Views :
Published Date :
Jan 27,2021