Printing basic example using friend function in C++


This is a C++ program that demonstrates the use of friend functions to access private data members of two different classes, A and B.

The program defines two classes, A and B, each with a private integer data member (x and y, respectively) and a public member function (setdata) to set the value of the data member.

The program also defines a friend function min, which takes objects of classes A and B as its arguments and compares their private data members (x and y, respectively) to find and print the minimum value.

In the main function, the program creates objects of classes A and B, sets their data members to values 10 and 20, respectively, and calls the min function, passing the objects as arguments. The min function then compares the data members of the objects and prints the minimum value (in this case, 10).

Source Code

#include<iostream>
using namespace std;
class B;
class A
{
   int x;
   public:
   void setdata(int i)
   {
       x=i;
   }
   friend void min(A,B);
};
class B
{
   int y;
   public:
   void setdata(int i)
   {
    y=i;
   }
   friend void min(A,B);
};
void min(A a,B b)
{
   if(a.x<=b.y)
   std::cout<<a.x<<std::endl;
   else
   std::cout<<b.y<<std::endl;
}
int main()
{
   A a;
   B b;
   a.setdata(10);
   b.setdata(20);
   min(a,b);
   return 0;
}
To download raw file Click Here

Output

10

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples