C++ friend class

By Prof. Fazal Rehman Shamil
Last modified on June 28th, 2020

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?




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?




Factorial using friend function in C++

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


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++.

Prof.Fazal Rehman Shamil (Available for Professional Discussions)
1. Message on Facebook page for discussions,
2. Video lectures on Youtube
3. Email is only for Advertisement/business enquiries.