Swapping Private data of classes

CASE:1

Given two numbers a & b, swap these two numbers using the friend function of C++. 

Examples: 

Input : a = 15, b = 9

Output : a = 9, b = 15

Input : a = 4, b = 16

Output : a= 16, b = 4

  • Approach: 
  • Create a class Swap, declare one variable in it, i.e., num, and create a constructor for inputs. Declare a friend function in it. Define the friend function outside the class scope by taking arguments as call by reference to pass the copy of Swap Object. Perform the swap operation.

CASE 2: 
Given two objects s1 & s2 of a class, swap the data members of these two objects using friend function of C++. 

Examples: 

Input : a = 6, b = 10
Output : a = 10, b = 6

Input : a = 4, b = 6
Output : a= 6, b = 4

Approach: 
Create a class Swap, declare one variable in it, i.e., num and create a constructor for inputs. Declare a friend function in it. Define the friend function outside the class scope by taking arguments as call by reference to pass the copy of Swap Object. Perform the swap operation.

Comments

Popular posts from this blog

About me

A set of documents that need to be classified, use the Naive Bayesian Classifier

Keras