C++ Program to add two numbers using friend function


In this program, You will learn how to add two numbers using friend function in C++.


friend void add();


Example: How to add two numbers using friend function in C++

Run it Now
#include<iostream>
using namespace std;

class Test {
private:
    int x, y, z;
public:

    void input() {
        cout << "Enter Two Numbers :";
        cin >> x>>y;
    }

    friend void add(Test &t);

    void display() {
        cout << "\nThe sum is :" << z;
    }
};

void add(Test &t) {
    t.z = t.x + t.y;
}

int main() {

    Test t;
    t.input();

    add(t);
    t.display();

    return 0;
}

Output:

Enter Two Numbers :10 20
The sum is :30