C++ friend class

Friend Class in C++
friend class is a class that can access the private and protected(also public) members of a class in which it is declared as a friend. We need to declare the class as a friend of another class to allow or request another class to access the private and protected members of that class.

Friend Class in CPP

Example Of Function Class

In this example, we have two classes T4 and Tutorials. The T4 class has two private data members ch and num, this class declares Tutorials as a friend class. This means that Tutorials can access the private members of T4, the same has been demonstrated in the example where the function disp() of Tutorials class accesses the private members’ num and ch. In this example, we are passing an object as an argument to the function.

How to access the C++ friend class?

Output

G

9

Friend Function in C++
If we declare a function as a friend in a class, then this function can access the private and protected members of that class. You must know that a global function can also be declared as a  friend function of the class.

Syntax of friend function in C++

class class_name_T4Tutorials
{

friend return_type function_name(arguments);

}

Now, you can define the friend function as a normal function to access the data of the class. No friend keyword is used in the definition.

class class_name

{

friend return_type function_Name(argument/s);

}
return_type function_Name(arguments)
{

// Private and protected data of class can be accessed from this function
// because it is a friend function of class.

}

How to access the C++ friend function?

Output

G

9

Factorial using friend function in C++

How to find factorial using friend function in C++?

Output

Please Enter a Number : 4

The factorial is : 24

Video Lecture

Examples of friend function in c++  | friend function in c++ pdf  | advantages of friend function in c++ | disadvantages of friend function in c++  | characteristics of friend function in c++  | friend function in c++ ppt  | why we use friend function in c++.