Questions: 1. Explain in detail about friend functions in C++ with example. 2. Explain friend function with an example.
Friend
Function
•
The friend function is a function that
is not a member function of the class but it can access the private and protected
members of the class.
•
The friend function is given by a
keyword friend.
•
These are special functions which are
declared anywhere in the class but have given special permission to access the
private members of the class.
#include<iostream>
using namespace std;
class test
{
int data;
friend int fun(int x);//declaration of friend function
public:
test()//constructor
{
data = 5;
}
};
int fun(int x)
{
test obj;
//accessing private
data by friend function
return obj.data + x;
}
int main()
{
cout <<
"Result is = "<< fun(4)<<endl;
}
Result is = 9
•
Following are some properties of friend
functions –
1. The friend function is not defined within the scope of the class.
2. It can
not be invoked by the object of particular class.
3.
It can be invoked like a normal function.
4.
This function can access the private
members of the class.
5.
Usually the objects of some class are passed as an argument to the friend
function.
6.
It must be declared with the keyword
friend.
1. Explain in detail
about friend functions in C++ with example.
2. Explain friend
function with an example.
Object Oriented Programming: Chapter 2: Classes and Objects : Tag: Oops, Computer Programming : C++ Programming | Object Oriented Programming - Friend Function
Object Oriented Programming (OOPs)
CS25C07 2nd Semester CSE, CSE(CY) Depts | 2025 Regulation | 2nd Semester 2025 Regulation
English Essentials II
EN25C02 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation
Tamils and Technology தமிழர்களும் தொழில்நுட்பமும்
UC25H02 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation
Linear Algebra
MA25C02 2nd Semester | 2025 Regulation
Applied Physics (CSIE) II
PH25C03 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation
Digital Principles and Computer Organization
CS25C06 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation
Basic Electrical and Electronics Engineering
EE25C01 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation
Object Oriented Programming (OOPs)
CS25C07 2nd Semester CSE, CSE(CY) Depts | 2025 Regulation | 2nd Semester 2025 Regulation
Re-Engineering for Innovation
ME25C05 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation
Object Oriented Programming (OOPs) - Laboratory
CS25C07 2nd Semester CSE, CSE(CY) Depts | 2025 Regulation | 2nd Semester 2025 Regulation