C++ Examples
- Write a C++ Program to print a welcome text in a separate line.
- Write a Program in C++ to add two numbers.
- C++ program for addition of two numbers using functions.
- Add two numbers in C++ using class.
- Addition of two numbers using call by reference in C++
- C++ program to write a program to add two numbers using call by value.
- Swapping of two numbers in C++ without using third variable.
- Swap two numbers in C++ using function.
- C++ program to swap two numbers using class.
- C++ program to swap two numbers using call by value.
- C++ program to swap two numbers using pointers.
- Write a program to swap private data members of two classes using friend function.
- write a program to add data objects of two different classes using friend function.
- Threading in C++.
- C++ thread lambda
- C++ thread lambda with parameter
- C++ thread lambda pass by reference
- Singleton C++ example
Write a program to swap private data members of two classes using friend function.
#include<iostream>
using namespace std;
class a1
{
private:
int x,y;
public:
//function to take input from the user
void input()
{
cout<<"Enter first number to swap ";
cin>>x;
cout<<"Enter second number to swap ";
cin>>y;
cout<<"Before swapping numbers are "<<x<<" "<<y<<endl;
}
//function for swapping of two numbers
friend void swapTwoNumbers(a1 &obj);
//function to display two swapped numbers
void display()
{
cout<<"The numbers after swapping are "<<x<<" "<<y;
}
};
void swapTwoNumbers(a1 &obj)
{
//Swapping of numbers using inbuilt swap funtion
swap(obj.x,obj.y);
}
int main()
{
a1 obj1;
obj1.input();
swapTwoNumbers(obj1);
obj1.display();
return 0;
} Output
Enter first number to swap 25
Enter second number to swap 46
Before swapping numbers are 25 46
The numbers after swapping are 46 25 Another method: Without inbuild swap function
#include<iostream>
using namespace std;
class a1
{
private:
int x,y,z;
public:
//function to take input from the user
void input()
{
cout<<"Enter first number to swap ";
cin>>x;
cout<<"Enter second number to swap ";
cin>>y;
cout<<"Before swapping numbers are "<<x<<" "<<y<<endl;
}
//function for swapping of two numbers
friend void swapTwoNumbers(a1 &obj);
//function to display two swapped numbers
void display()
{
cout<<"The numbers after swapping are "<<x<<" "<<y;
}
};
void swapTwoNumbers(a1 &obj)
{
//Swapping of numbers
obj.z = obj.x;
obj.x = obj.y;
obj.y = obj.z;
}
int main()
{
a1 obj1;
obj1.input();
swapTwoNumbers(obj1);
obj1.display();
return 0;
}
Enter first number to swap 23
Enter second number to swap 45
Before swapping numbers are 23 45
The numbers after swapping are 45 23