C++ Object Class Friend Function
A friend function in C++ is a function that is granted access to the private and protected members of a class. It is declared inside the class but defined outside the class. The purpose of a friend function is to allow external functions to access private and protected data members of a class.
Syntax
The syntax of a friend function is as follows:
class MyClass {
private:
int x;
public:
friend void friendFunction(MyClass&);
};
void friendFunction(MyClass& obj) {
obj.x = 10;
}
In the above example, the function friendFunction()
is a friend function declared inside the class MyClass
. It takes an object of MyClass
as an argument and modifies the private member x
.
Example
#include<iostream>
using namespace std;
class MyClass {
private:
int x;
public:
MyClass() {
x = 0;
}
friend void friendFunction(MyClass&);
};
void friendFunction(MyClass& obj) {
obj.x = 10;
}
int main() {
MyClass obj;
cout << "Before friend function: " << obj.x << endl;
friendFunction(obj);
cout << "After friend function: " << obj.x << endl;
return 0;
}
Output
Before friend function: 0
After friend function: 10
Explanation
In the above example, we have defined a class MyClass
with a private member x
and a friend function friendFunction()
. The function friendFunction()
takes an object of MyClass
as an argument and modifies the private member x
.
In the main()
function, we create an object obj
of MyClass
. Before calling the friend function, the value of x
is 0. After calling the friend function, the value of x
is changed to 10.
Use
A friend function can be used in the following scenarios:
- To access private or protected members of a class from outside the class
- To make two or more classes communicate with each other without exposing their implementation details
- To simplify the implementation of operators such as
<<
and>>
Important Points
- A friend function can be declared inside or outside the class
- A friend function cannot access members of a class directly. It has to be passed an object of the class as an argument
- Friends are not members of a class but can be part of the namespace in which the class is defined
- Friendship is not transitive. If class A is a friend of class B and class B is a friend of class C, then class A is not automatically a friend of class C.
Summary
In summary, a friend function in C++ is a function that is granted access to the private and protected members of a class. It is declared inside the class but defined outside the class. A friend function can be used to access private or protected members of a class from outside the class, make two or more classes communicate with each other without exposing their implementation details, and simplify the implementation of operators.