Explain use of friend function in C++ with examples?

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:

  1. global function,
  2. 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;

class Square
  double side;

   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;

int main()
  Square S;
  plength(S); //friend function for print length
  return 0;


Length of Square 13.0

cpp interview questions

Would you like to see your article here on tutorialsinhand. Join Write4Us program by

About the Author
Subhajit Guha Thakurta
Page Views :    Published Date : Jan 27,2021  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!