/    /  CPP- Object as Function Arguments

Object as Function Arguments

 

Object as Function Arguments Similar to variables, object can be passed to functions. Here are the two methods to pass an argument to a function:

 

  1. Pass-by-value: A copy of the integer (actual object) is sent to the function and assigned to the object of the called function (formal object). Actual and formal copies of objects are stored in different parts of the memory. Therefore, the changes carried out in the formal object are not reflected in the real object.
  2. Pass-by-reference: Only the address for the subject is sent to the function. The function receives an address for the current object. The formal argument is reference/direct to the real object. As a result, the changes made in the object are reflected in the real object. This method is useful because an address is passed to the function and the duplication of the object is blocked. 

 

For example,

#include <iostream>
using namespace std;
class Complex
{ private:
 int real, imag;
 public:
Complex(int r=0,int i=0)

real = r; imag = i;
 }
 void setComplex(void)

 cout << "Enter real and imaginary parts";
 cin >> this->real; // cin>>real;
 cin >> this->imag; // cin>>image; 
 }
 Complex add(const Complex & c)

 Complex comp;
 comp.real = this->real + c.real;
 comp.imag = this->imag + c.imag;
 return comp;
 }
 void printComplex(void)
 {
 cout << "Real : " << this->real << endl;
 cout<< "Imaginary" << this->imag << endl;
 }
};
int main()
{ 
 Complex a, b, c, d;
 cout << "Enter first complex no " << endl;
 a.setComplex();
 cout << "Enter second complex no"<< endl;
 b.setComplex();
 /* Adding two complex numbers */
 cout << "Addition of a and b : " << endl;
 c = a.add(b);
 c.printComplex();
 return 0;
}

Output: