Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to swap the values in the private data members of two class

C++ Code Example — Miscellaneous Programs

ADVERTISEMENT

WAP to swap the values in the private data members of two class

Objective

Write a C++ program to swap private data members between two different classes using a Friend Class.

Algorithm / Approach

  1. Create class A with a private variable a.
  2. Declare friend class B; completely inside class A.
  3. Create class B with a private variable b and a swap2() function.
  4. Inside swap2(), create an object of A (A obj;) and access its private variable directly (obj.a) to perform a swap.
main.cpp
#include<iostream>
using namespace std;
class A {
 int a;
 friend class B;
};
class B {
 int b;
 public:
 void swap2() { 
  A obj;
  cout<<"Enter Value for a ";
  cin>>obj.a;
  cout<<"Enter Value for b ";
  cin>>b;
  int temp = obj.a;
  obj.a = b;
  b = temp;
  cout<<"After Swapping \n";
  cout<<"Value in A "<< obj.a<< endl;
  cout<<"Value of B "<< b<< endl;
 }
};
int main() {
 B b;
 b.swap2();
 return 0;
}

Expected Output

Enter Value for a 10
Enter Value for b 30
After Swapping
Value in A 30
Value in B 10

Explanation of the Program

  • The golden rule of Object-Oriented Programming is that private variables cannot be accessed from outside their class.
  • The friend keyword is a strict exception to this rule. By declaring Class B as a "friend" inside Class A, Class A is trusting Class B with full, unrestricted access to all of its private secrets.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT