Let’s begin with a programming example in which I will show you how a friend function Can access private, protected, and public members of a class.

C++ Example: Friend function Can access private data members of a class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> using namespace std; class one { private: int n1=1; public: friend int add(one); }; int main() { one object1; cout<<"Sum: "<< add(object1); return 0; } int add(one object1) { return (object1.n1 + 1); } |
Output
Sum: 2
C++ Example: Friend function Can access protected data members of a class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> using namespace std; class one { protected: int n1=1; public: friend int add(one); }; int main() { one object1; cout<<"Sum: "<< add(object1); return 0; } int add(one object1) { return (object1.n1 + 1); } |
Output
Sum: 2
C++ Example: Friend function Can access public data members of a class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> using namespace std; class one { public: int n1=1; public: friend int add(one); }; int main() { one object1; cout<<"Sum: "<< add(object1); return 0; } int add(one object1) { return (object1.n1 + 1); } |
Output
Sum: 2