Sitemap
Surajkh

Surajkh

Passionate Software Developer

Friend Function in C++(Cpp)

2 min readDec 23, 2022

Friend Function is basically a function which has access to private and protected data members of a class(outside the scope of a Particular Class).

Class by default has a private scope for all the data members and member functions,inorder to access private and protected data members outside the scope of a particular we maek use of Friend Function.

Get Surajkh’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s us Consider The below Code snippet :

Press enter or click to view image in full size
Friend Functions in C++(Cpp)

The Friend Function Prototype is depicted as followed:

Press enter or click to view image in full size
Friend Function Prototype

Now Lets consider the Implementation of Friend Function over here:

Press enter or click to view image in full size
Implementation of Friend Function

Now with the implementation of Friend Function we are able to access the Private data members of class(student_name and roll_no) even when these private data members have a restricted scope within the class(private scope) over here.

Now lets analyse the Output for the above defined Program:

Press enter or click to view image in full size
Output Pic

Here the User is prompted to Insert Student Name along with Roll number,after entering the respective details,this Object is being Passed as a Parameter to the Friend Function,now the Friend Function is able to access the Data Members of the Above defined Class and generates the Final Output over here.

--

--

Surajkh
Surajkh

Written by Surajkh

0 followers

Passionate Software Developer