Friend Function
- A friend function is a special function in C++ which in spite of not being a member function of a class has the privilege to access private and protected data of a class.
- A friend function is a non-member function or an ordinary function of a class, which is declared by using the keyword “friend” inside the class. By declaring a function as a friend, all the access permissions are given to the function.
- The keyword “friend” is placed only in the function declaration but not in the function definition.
- When the friend function is called neither the name of the object nor the dot operator is used. However, it may accept the object as an argument whose value it wants to access.
- A friend function can be declared in any section of the class i.e. public, private, or protected.
Declaration of friend function in C++
Syntax:
class <class_name> {
friend <return_type> <function_name>(argument/s);
};
Example_1: Find the largest of two numbers using Friend Function
C++
#include <iostream> using namespace std; class Largest { int a, b, m; public : void set_data(); friend void find_max(Largest); }; void Largest::set_data() { cout << "Enter the first number : " ; cin >> a; cout << "\nEnter the second number : " ; cin >> b; } void find_max(Largest t) { if (t.a > t.b) t.m = t.a; else t.m = t.b; cout << "\nLargest number is " << t.m; } int main() { Largest l; l.set_data(); find_max(l); return 0; } |
Output
Enter the first number : 789
Enter the second number : 982
Largest number is 982
Functions in C++
A function is a set of statements that takes input, does some specific computation, and produces output. The idea is to put some commonly or repeatedly done tasks together to make a function so that instead of writing the same code again and again for different inputs, we can call this function.
In simple terms, a function is a block of code that runs only when it is called.
Syntax:
Example:
C++
// C++ Program to demonstrate working of a function #include <iostream> using namespace std; // Following function that takes two parameters 'x' and 'y' // as input and returns max of two input numbers int max( int x, int y) { if (x > y) return x; else return y; } // main function that doesn't receive any parameter and // returns integer int main() { int a = 10, b = 20; // Calling above function to find max of 'a' and 'b' int m = max(a, b); cout << "m is " << m; return 0; } |
Output
m is 20
Time complexity: O(1)
Space complexity: O(1)