Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when to pass and return by reference to a function in c++

Tags:

c++

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?

like image 616
Dhruv Shekhawat Avatar asked Dec 25 '22 15:12

Dhruv Shekhawat


2 Answers

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.

like image 153
ForEveR Avatar answered Jan 08 '23 20:01

ForEveR


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.

like image 43
Sergey Kalinichenko Avatar answered Jan 08 '23 21:01

Sergey Kalinichenko