C++ Program to swap two numbers using friend function


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


friend void swap();


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

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

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

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

    friend void swap(Test &t);

    void display() {
        cout << "\nAfter Swap x is :" << x;
        cout << "\nAfter Swap y is :" << y;
    }
};

void swap(Test &t) {
    t.temp = t.x;
    t.x = t.y;
    t.y = t.temp;

}

int main() {

    Test t;
    t.input();

    swap(t);
    t.display();

    return 0;
}

Output:

Enter Two Numbers :10 20
After Swap x is :20
After Swap y is :10