wds
wds

Reputation: 61

Passing a reference argument and returning a reference

I've been reading about operator overloading, and have learned that if you return a reference from a function that you can cascade overloaded operators.

My question is this. In order to return a reference, do you need to pass a reference to a function, or will the value do?

e.g. Are both valid?

ostream &operator<<(ostream output, string &label);

and

ostream &operator<<(ostream &output, string &label);

Will the first also return a valid reference to the output stream argument passed to the function, or do you need to pass in the output stream object as a reference to return it as a reference?

Upvotes: 1

Views: 598

Answers (1)

R Sahu
R Sahu

Reputation: 206737

You cannot use

std::ostream &operator<<(std::ostream output, std::string &label);

since std::ostream does not have a copy constructor.

Even if std::ostream had a copy constructor, using the above interface would cause the following problems.

Problem 1

Returning a reference to the input argument would be a problem. The object will not be alive after the function returns. Hence, the returned reference would be dangling reference as soon as the function returned. Using the dangling reference would cause undefined behavior.

Problem 2

This is hypothetical.

Imagine what would happen if you used:

std::ofstream outfile("myoutput.txt");
outfile << "A string.";

The call would result in object slicing. You would lose the std::ofstream-ness of the object. Where would the output go in that function? It certainly won't go to the file.


Stick with

std::ostream &operator<<(std::ostream &output, std::string const& label);

PS Yes, I did change the type of the second argument to const&.

Upvotes: 2

Related Questions