Friend function in C++ with Programming example
In this tutorial, we will Learn:
What is friend function in C++ with Programming example?
Explain how one can bridge two classes using the friend function. Write a C++ program to find the sum of two numbers using bridge function add()
Solution:
Video Tutorial:
A class can have global non-member functions and member functions of other classes as friends.
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
Summary:
In this article, we understood the concept of the Friend Functions in C++ with a simple Programming example and wrote a C++ program to find the sum of two numbers using friend function add().
If you like the tutorial share it with your friends. Like the Facebook page for regular updates and YouTube channel for video tutorials.