Program to swap values of Two Variables using constructor in C++ || Constructor || C++
In this, we are going to see how to swap Value of Two Variable using Constructor, in C++.
 


The Code given below can be used in TURBO C++ Compilers: -

#include <iostream.h>
#include<conio.h>

class swapping
{
private:
    float x, y;

public:
    swapping(float a, float b)
    {
        float temp;

        temp = a;
        a = b;
        b = temp;

        x = a;
        y = b;
    }

    int getA()
    {
        return x;
    }

    int getB()
    {
        return y;
    }
};

void main()
{
    clrscr();
    float a, b;
    cout << "Enter 2 numbers:-\n";
    cin >> a >> b;

    cout << "Numbers before swapping:- \na = " << a << "\nb = " << b;

    //Calling the constructor & swapping the terms
    swapping p(a, b);

    cout << "\nNumbers after swapping:-\na = " << p.getA() << "\nb = " << p.getB();
    getch();
}

//..........Coded by YASH ALAPURIA


The Code given below can be used in gcc/g++ Compilers: -

#include <iostream>
#include <stdlib.h>
using namespace std;

class swapping
{
private:
    float x, y;

public:
    swapping(float a, float b)
    {
        float temp;

        temp = a;
        a = b;
        b = temp;

        x = a;
        y = b;
    }

    int getA()
    {
        return x;
    }

    int getB()
    {
        return y;
    }
};

int main()
{
    system("cls");
    float a, b;
    cout << "Enter 2 numbers:-\n";
    cin >> a >> b;

    cout << "Numbers before swapping:- \na = " << a << "\nb = " << b;

    //Calling the constructor & swapping the terms
    swapping p(a, b);

    cout << "\nNumbers after swapping:-\na = " << p.getA() << "\nb = " << p.getB();
    return 0;
}

//..........Coded by YASH ALAPURIA


#ENJOY CODING

Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post