in C++ How to pass and return an object from a function?

 in C++ How to pass and return an object from a function?


 in C++ How to pass and return object from a function?In C++ programming, objects can be passed to a function in a similar way as structures.

How to pass objects to a function?

Pass Object to a function in C++

Example 1: Pass Objects to Function

C++ program to add two complex numbers by passing objects to a function.
  1. #include <iostream>
  2. using namespace std;
  3. class Complex
  4. {
  5. private:
  6. int real;
  7. int imag;
  8. public:
  9. Complex(): real(0), imag(0) { }
  10. void readData()
  11. {
  12. cout << "Enter real and imaginary number respectively:"<<endl;
  13. cin >> real >> imag;
  14. }
  15. void addComplexNumbers(Complex comp1, Complex comp2)
  16. {
  17. // real represents the real data of object c3 because this function is called using code c3.add(c1,c2);
  18. real=comp1.real+comp2.real;
  19. // imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2);
  20. imag=comp1.imag+comp2.imag;
  21. }
  22. void displaySum()
  23. {
  24. cout << "Sum = " << real<< "+" << imag << "i";
  25. }
  26. };
  27. int main()
  28. {
  29. Complex c1,c2,c3;
  30. c1.readData();
  31. c2.readData();
  32. c3.addComplexNumbers(c1, c2);
  33. c3.displaySum();
  34. return 0;
  35. }
Output
Enter real and imaginary number respectively:
2
4
Enter real and imaginary number respectively:
-3
4
Sum = -1+8i

How to return an object from the function?


Return object from a function in C++

Example 2: Pass and Return Object from the Function

In this program, the sum of complex numbers (object) is returned to the main() function and displayed.
  1. #include <iostream>
  2. using namespace std;
  3. class Complex
  4. {
  5. private:
  6. int real;
  7. int imag;
  8. public:
  9. Complex(): real(0), imag(0) { }
  10. void readData()
  11. {
  12. cout << "Enter real and imaginary number respectively:"<<endl;
  13. cin >> real >> imag;
  14. }
  15. Complex addComplexNumbers(Complex comp2)
  16. {
  17. Complex temp;
  18. // real represents the real data of object c3 because this function is called using code c3.add(c1,c2);
  19. temp.real = real+comp2.real;
  20. // imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2);
  21. temp.imag = imag+comp2.imag;
  22. return temp;
  23. }
  24. void displayData()
  25. {
  26. cout << "Sum = " << real << "+" << imag << "i";
  27. }
  28. };


Comments

Popular posts from this blog

C++ Templates ?

C++ Program to Print Number Entered by User

Educational Website