Raj Kumar
Computer Science And Engineering

Friend function in C++ with Programming example

Object Oriented Concepts

Explanation

1158    0
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:   
   Raj Kumar
Computer Science And Engineering

More Questions from Object Oriented Concepts Module 1