StudyLover
  • Home
  • Study Zone
  • Profiles
  • Contact us
  • Sign in
StudyLover 11. Program to swap private data members of classes named `class1` and `class2` using a friend function.
Download
  1. C++ Programs list
10. Program to calculate the average of all elements in an array. : 12. Program to design a class representing complex numbers and perform addition and multiplication using operator overloading.
C++ Programs list

1.      Program to swap private data members of classes named `class1` and `class2` using a friend function.

  1. #include <iostream.h>

  2. #include<conio.h>

  3. class class2;

  4.  

  5. class class1 {

  6. private:

  7.     int x;

  8.  

  9. public:

  10.     class1(int x) : x(x) {}

  11.  

  12.     friend void swap(class1& obj1, class2& obj2);

  13.  

  14.     void print() {

  15.         cout << "Class1: " << x << endl;

  16.     }

  17. };

  18.  

  19. class class2 {

  20. private:

  21.     int y;

  22.  

  23. public:

  24.     class2(int y) : y(y) {}

  25.  

  26.     friend void swap(class1& obj1, class2& obj2);

  27.  

  28.     void print() {

  29.         cout << "Class2: " << y << endl;

  30.     }

  31. };

  32.  

  33. void swap(class1& obj1, class2& obj2) {

  34.     int temp = obj1.x;

  35.     obj1.x = obj2.y;

  36.     obj2.y = temp;

  37. }

  38.  

  39. int main() {

  40.     class1 obj1(10);

  41.     class2 obj2(20);

  42.  

  43.     cout << "Before swapping:\n";

  44.     obj1.print();

  45.     obj2.print();

  46.  

  47.     swap(obj1, obj2);

  48.  

  49.     cout << "\nAfter swapping:\n";

  50.     obj1.print();

  51.     obj2.print();

  52.     getch();

  53.     return 0;

  54. }

10. Program to calculate the average of all elements in an array. 12. Program to design a class representing complex numbers and perform addition and multiplication using operator overloading.
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website