Friend Function Program in C++

This C++ program demonstrates the use of keyword friend in classes. The program creates two classes ‘X’ and ‘Y’ and declares one class as ‘friend’ in another. By declaring friend, we mean that the friend class ‘Y’ will gain access to all the data members of the class ‘X’. The member functions of the friend class ‘Y’ can now change the values of data member of objects of class ‘X’ when passed as parameters.

Here is the source code of the C++ program demonstrates the use of keyword friend in classes. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Demonstrate the use of Keyword Friend
  3.  */
  4.  #include <iostream>
  5.  
  6. class X {
  7.     private:
  8.         int j;
  9.     protected:
  10.         int k;
  11.     public:
  12.         X(int jj = 1, int kk = 2) : j(jj), k(kk) {}
  13.         friend class Y;
  14.         friend void fun();
  15. };
  16.  
  17. class Y {
  18.     int l;
  19.     public:
  20.         Y(int ll = 0) : l(ll) {}
  21.         void change(const X& x);
  22.         void printValue()
  23.         {
  24.             std::cout << "Y::l = " << l << std::endl;
  25.         }
  26. };
  27.  
  28. void Y::change(const X& x)
  29. {
  30.     l = x.j;
  31.     std::cout << "Y::change() : Y::l is now X::j " << std::endl;
  32. }
  33.  
  34. void fun()
  35. {
  36.     X x;
  37.     std::cout << "fun::X::j  = " << x.j << std::endl;
  38. }
  39.  
  40. int main()
  41. {
  42.     X x;
  43.     Y y;
  44.  
  45.     y.printValue();
  46.     fun();
  47.     y.change(x);
  48.     y.printValue();
  49. }

$ a.out
Y::l = 0
fun::X::j  = 1
Y::change() : Y::l is now X::j
Y::l = 1

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.