I have a program which adds two complex numbers using the + operator overloading. The program is:
#include<iostream>
class Complex
{
int a, b;
public:
Complex()
{
std::cout<<"\n Normal constructor ";
}
void setData(int x, int y)
{
a = x; b = y;
}
void showData()
{
std::cout<<"a = "<<a<<std::endl<<"b = "<<b<<std::endl;
}
Complex operator + (Complex c)
{
Complex temp;
temp.a = a + c.a;
temp.b = b + c.b;
return temp;
}
Complex(Complex &z)
{
std::cout<<"\n The copy constructor is called ";
}
};
int main()
{
Complex c1, c2, c3;
c1.setData(2, 3);
c2.setData(4, 5);
c3 = c1+c2;
c3.showData();
return 0;
}
Here when I do not write the copy constructor explicitly then this program is giving correct output. But after writing copy constructor the output is garbage value and I want to know why is the program producing garbage value?
Output instance:
Normal constructor
Normal constructor
Normal constructor
The copy constructor is called
Normal constructor a = -1270468398
b = 32769
Please tell that "what is happening after c3 = c1+2;
is executed?"