WAP to add two numbers using friend function
Objective
Write a C++ program to add two numbers by accessing private class variables using a Friend Function.
Algorithm / Approach
- Create
class Testwith private variablesa,b,c. - Inside the class, declare
friend void add();. - Write the
add()function completely outside of the class. - Inside
add(), instantiate aTestobject and directly access its private variables to perform addition. - Call
add()normally frommain().
main.cpp
#include<iostream>
using namespace std;
class Test {
int a, b, c;
friend void add();
};
void add() {
Test t;
cout<<"Enter Two Numbers ";
cin>>t.a>>t.b;
t.c = t.a+t.b;
cout<<"Sum = "<< t.c<< endl;
}
int main() {
add();
return 0;
}
Expected Output
Enter Two Numbers 10 20 Sum = 30
Explanation of the Program
- Similar to a Friend Class, a Friend Function is an independent, global function that has been granted VIP access to a class's private variables.
- Even though the function is declared inside the class with the
friendkeyword, it is NOT a member of the class. It is a normal global function that can be called directly without needing an object (e.g.,add(), nott.add()).
Complexity
Time Complexity
O(1)
Space Complexity
O(1)