C++ Friend Function
The functions which are declared as a friend of the class can access the private or protected data members is called Friend Function.
The Friend Function may be either declared or defined within the scope of a class.
The keyword of a friend must be given before the function declaration or definition.
The keyword friend should not be repeated when the class is defined outside the class.

The prototype of the Friend function appears in the definition of the class and friends are not the members of the class.
To declare the friend function of the class as precede the prototype of the function in the definition of the class with keyword Friend.
Syntax:
friend data_type function_name(argument);
Example:
#include <iostream>
using namespace std;
class Rectangle{
private:
int length=5, breadth=6;
float area;
public:
void get_data(); //member function
friend void show_data(Rectangle); //friend function
};
void Rectangle::get_data()
{
cout << "Enter the length and breadth value: " ;
cout << length << " " << breadth << endl;
area= length * breadth;
}
void show_data(Rectangle r1)
{
cout << "Area of the Rectangle: " << r1.area;
}
int main(){
Rectangle r1;
r1.get_data(); //member function call using object
show_data(r1); //friend function call without object
return 0;
}
Friend Class
The class which are declared as a friend of the class can access the private or protected data members. The private members of one class can be accessed from the member functions of another class is called friend class.
Example:
#include <iostream>
using namespace std;
class Rectangle{
private:
int length=5, breadth=6;
float area;
public:
friend class Result; // friend class
};
class Result{
public:
void show_data(Rectangle r1)
{
cout << "Enter the length and breadth value: " ;
cout << r1.length << " " << r1.breadth << endl;
r1.area= r1.length * r1.breadth;
cout << "Area of the Rectangle: " << r1.area;
}
};
int main(){
Rectangle r1;
Result r2;
r2.show_data(r1);
return 0;
}
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.