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
- Create
class Awith a private variablea. - Declare
friend class B;completely insideclass A. - Create
class Bwith a private variableband aswap2()function. - 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
friendkeyword 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)