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++.


class Add{
  //statement
};

C++ Program to add two numbers using friend function

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

#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 << "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
sum is:30