#include <iostream>
using namespace std;
class Complex {
private:
int real;
int img;
public:
//Constructor
Complex(int a=0, int b=0);
//Copy Constructor
Complex (Complex &c); //Here why do I have to use reference why can't I use call by value like in
//function add
//function
Complex add(Complex c);
void display();
};
Complex::Complex(int a, int b) {
real = a;
img = b;
}
Complex::Complex (Complex &c) {
real = c.real;
img = c.img;
}
Complex Complex::add(Complex c) {
Complex temp;
temp.real = real + c.real;
temp.img = img + c.img;
return temp;
}
void Complex::display() {
cout<<real<<" +i"<<img<<endl;
}
int main() {
Complex c1(2,4), c2(3,5), c3(c1), c4;
c4=c1.add(c2);
c1.display();
c2.display();
c3.display();
c4.display();
return 0;
}
I couldn't understand the reason of using pass by reference there. If I try to use pass by value, I get an Compiler error message: error: invalid constructor; you probably meant Complex(const Complex&)