first I made a complex class in c++ which had two member datas -real and imaginary.(of the form a+ib). when I tried to overload << operator for complex class object as follows-
friend ostream operator<<(ostream ,complex ); in .h file
ostream operator <<(ostream o,complex c){
o<<"real part"<<c.real;
o<<"imaginary part<<c.imaginary;
return o;
}
in .cpp file, it does not work and rather opens an ios_base file and shows an error there. but the same code overloads << perfectly when i pass by reference and return by reference as follows-
ostream& operator <<(ostream& o,complex& c)
{
//same as before
};
i dont understand how passing and returning by reference helps?
std::ostream is not-copyable type type. You cannot do copy of o
, so you must receive it by reference and return it by reference.
The rule for using a reference vs. not using a reference is simple: if you want to use the same object as in the caller, pass it by reference; if you want to make a copy of the object being passed, do not use reference.
In some cases you can pass an object only by reference. Specifically, when it is incorrect to copy an object, designers of its class can prohibit copying. Objects that represent input/output and synchronization resources are often non-copyable, meaning that you must pass them by reference or by pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With