Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to add two numbers using friend function

C++ Code Example — Miscellaneous Programs

ADVERTISEMENT

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

  1. Create class Test with private variables a, b, c.
  2. Inside the class, declare friend void add();.
  3. Write the add() function completely outside of the class.
  4. Inside add(), instantiate a Test object and directly access its private variables to perform addition.
  5. Call add() normally from main().
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 friend keyword, 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(), not t.add()).

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT