c++ - Doubts in a code to test the use of assignment operator -
i writing code test use of assignment operator , copy constructor. code follows:
#include <iostream> #include <algorithm> using namespace std; class fun { int i; public: fun():i(1) {i=1;cout<<"in: cons\n";} ~fun() {cout<<"in: des\n";} fun& operator=(fun b) { cout<<"in: assignop\n"; swap(this->i, b.i); return *this; } fun(fun& b) { cout<<"in: copy cons\n"; b.i = this->i; } void print() { cout<<i<<endl; } }; main() { fun a; fun b; b = a; a.print(); }
and here output of code:
in: cons
in: cons
in: copy cons
in: assignop
in: des
-1216991244
in: des
in: des
now, there 2 things can't understand output.
firstly, why code going in copy constructor function? secondly, why value of 'i' being printed garbage instead of '1'?
i newbie excuse me if doubt obvious.
b = a;
this causing assignment operator called. reason see copy cons
in output because assignment operator takes argument value. a
copied assignment operator function, requires copy constructor used.
both copy constructors , copy assignment operators take arguments const
reference.
the reason garbage value because have line backwards:
b.i = this->i;
it should be:
this->i = b.i;
otherwise, copy constructor copies indeterminate value of this->i
object copying from.
Comments
Post a Comment