Write a C++ program to swap the value of private data members from 2 different classes.

This is a perfect example to understand the concept of access specifiers and also how we can exchange private data between two classes. We can simply the getters and setters in order to swap the private data members of 2 classes.

Tutorial 📺

First, create a class and name it Number1. It has one data member n1 and three member functions: get(), set() and display().

Similarly, create another class and name it Number2. It also has one data member n2 and three member functions: get(), set() and display().

Next, create an object of each class and name them num1 and num2, respectively. Now, set the values of both object by calling the member functions with the help of their respective objects, set the values for num1 to 10 and num2 to 20.

Now, implement the logic of swapping 2 values using 3 variables if you remember or you can check out the code below:

Code 💻

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

class Number1
{
  private:
    int n1;
  public:
    int get()
    {
      return n1;
    }
    void set(int n)
    {
      n1 = n;
    }
    void display()
    {
      cout << "\nN1 = " << n1 << endl;
    }
}; // class Number1 ends here


class Number2
{
  private:
    int n2;
  public:
    int get()
    {
      return n2;
    }
    void set(int n)
    {
      n2 = n;
    }
    void display()
    {
      cout << "\nN2 = " << n2 << endl;
    }
}; // class Number2 ends here

void main()
{
  clrscr();
  Number1 num1; // obj of class Number1
  Number2 num2; // obj of class Number2
  num1.set(10); // Set value of member variable n1 to 10
  num2.set(20); // Set value of member variable n2 to 20
  cout << "Before Swapping the values:" << endl;
  num1.display(); // display the value of n1
  num2.display(); // display the value of n2
  // ---- Let's swap the values of private data members of these two objects ----
  int temp, temp2;
  temp = num1.get();
  // num1.set(num2.get());
  temp2 = num2.get();
  num1.set(temp2);
  num2.set(temp);
  cout << "\n\nAfter Swapping the values:" << endl;
  num1.display(); // display the value of n1
  num2.display(); // display the value of n2
  getch(); 
}

Output 😃

Before Swapping the values:
N1 = 10
N2 = 20

After Swapping the values:
N1 = 20
N2 = 10

Categorized in: