Friend function in C++ with Programming example


The friend function is a function that is not a member function of the class but it can access the private and protected members of the class.
The friend function is given by a keyword friend.
These are special functions which are declared anywhere in the class but have given special permission to access the private members of the class.

Following program demonstrates the C++ program to find the sum of two numbers using bridge function add().

#include<iostream>
 using namespace std;

 class addtwonumbers
 {
     int x, y;
     public:
         addtwonumbers()
         {
             x = 0;
             y = 0;
         }
         addtwonumbers(int a, int b)
         {
             x = a;
             y = b;
         }
         friend int add(addtwonumbers &obj);
 };

 int add(addtwonumbers &obj)
 {
     return (obj.x+ obj.y);
 }

 int main()
 {
     addtwonumbers a1;
     cout<<"Sum is: "<<add(a1)<<endl;
     addtwonumbers a2(10, 20); 
     cout<<"Sum is: "<<add(a2)<<endl;
 }

OUTPUT:
Sum is: 0 Sum is: 30


Share to whatsapp

More Questions from Object Oriented Concepts Module 1

What is an inline function? Write a C++ program to find the maximum of two numbers using inline function.
View
Friend function in C++ with Programming example
View
Static member and count the number of objects in C++
View
Function Overloading with an Example in C++
View
Basic concepts (features) of Object-Oriented Programming C++
View
What are the basic differences between the POP (Procedure Oriented Programming) and OOP (Object Oriented Programming)?
View