1

I'm confused on why exactly I need to use references for the return type and parameter list in this example from my book below. Is their any reason besides that it takes up less memory than having everything being copied over using pass by value? Or does it have to deal more with if I wanted to do cascading?

istream &operator>>( stream &input, PhoneNumber &number)
{
//input whatever
return input;
}
1
  • It means you can chain calls together. cin >> a >> b >> c; Commented Apr 16, 2012 at 7:17

2 Answers 2

4

Because a) streams are not copyable, b) getting input from a stream means mutating it, so you need to modify the original and not a copy (however would that be realised). And reference to PhoneNumber should be obvious — you're getting input from the stream and into that object. If you'd pass it by copy, it wouldn't be visible outside of the operator, which makes the entire exercise rather pointless.

Sign up to request clarification or add additional context in comments.

Comments

1

The biggest reason why you use pointers and references is not because it lets you use less memory (although it certainly does), but because it lets you use less time. Copying objects takes time, you often need to allocate additional memory, and then deallocate it in the end.

Even more importantly, objects such as streams are not meant to be copied at all: they contain internal state that is relevant to a physical object, - a file on disk or a network stream, - and their associated buffers, that does not make much sense to copy.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.