I am getting these following errors
prog.cpp: In function ‘int main()’:
prog.cpp:18:15: error: invalid initialization of non-const reference of type ‘cmplex&’ from an rvalue of type ‘cmplex’
cmplex c3=cmplex();
^~~~~~~~
prog.cpp:12:1: note: initializing argument 1 of ‘cmplex::cmplex(cmplex&)’
cmplex(cmplex &c){a=c.a;b=c.b;cout<<"its inside copy constructor 1"<<endl;cout<<a<<b<<endl;}
^~~~~~
Why is this happening?What should I do to solve this problem?
When a function takes a non-const references as argument it implies that the function wants to modify the argument, but modifying a temporary object is usually pointless because it will get destroyed as soon as the function returns so no one gets to see the changes that was made. Since it's usually a mistakes to pass temporary objects to functions that modifies the object it has been made an error.
1 2 3 4
cmplex c3 = cmplex(); // complex() creates a temporary object that will get
// destroyed when this line is finished executing. If
// the copy constructor modified the temporary object
// we wouldn't notice.
ctor A 1 2
ctor B 3 42
ctor A 4 5
assign 4 5
ctor A 6 7
assign 6 7
ctor C 7 13
copy ctor 6 7
assign 4 5
assign 4 5
The cmplex(8) on line 26 is an unnamed temporary object. It does not exist after the statement.
The call to copy constructor wants to create a reference to its argument object.
If you create a reference to temporary, the reference could outlive the referred object.
Lets assume that you put $1000 to your pocket. You remember that you did so. Later, you would like to use some of that money. Alas, it was not "real" $1000, but a time-limited offer. The offer has already expired. You have a problem.
You can create a const reference (like the assignment operator does). That extends the lifetime of the temporary.