Difference between Friend Function and Friend class in C++

Satish Patil
2 min readJan 8, 2023

--

In C++, a friend function is a function that is declared with the keyword friend in the class body, but defined outside of the class. Friend functions are not member functions of the class, but they have access to the private and protected members of the class.

Declaring a function as a friend allows the function to access the private and protected members of the class. This is often used to allow a function to perform operations on the class that would otherwise be forbidden by the class’s access controls.

Here is an example of a class with a friend function:

class MyClass {
private:
int x;
friend void myFriendFunction(MyClass& obj);
};
void myFriendFunction(MyClass& obj) {
// Access the private members of obj
obj.x = 10;
}

A friend class is a class that is declared with the keyword friend in the class body of another class. Like friend functions, friend classes are not member classes of the class in which they are declared, but they have access to the private and protected members of the class.

Here is an example of a class with a friend class:

class MyClass {
private:
int x;
friend class MyFriendClass;
};

class MyFriendClass {
public:
void doSomething(MyClass& obj) {
// Access the private members of obj
obj.x = 10;
}
};

Friendship is not transitive. For example, if class B is a friend of class A, and class C is a friend of class B, class C does not automatically become a friend of class A. Friendship must be explicitly declared in each class.

--

--