0

In a code a professor of mine developed, there's a class called Node. In that class, operators << and >> are overloaded as follows:

// Overloaded write operator
friend std::ostream& operator<<(std::ostream& os, const Node& obj);
// Overloaded input operator
friend std::istream& operator>>(std::istream& is, Node& obj);

Does anyone know:

  • The meaning of const in the first signature, and why is not possible to use const in the second one?
  • The purpose of & after Node in the second signature.
jotik
  • 17,044
  • 13
  • 58
  • 123

3 Answers3

1

const Node& obj means that the argument obj is a reference to a constant Node object.

Node& obj means that the argument obj is a reference to a mutable (non-constant) Node object.

The logic here is, that when you read write something to a stream, you don't need to modify that something, hence it can be const. But when you read something from a stream and write it to some object, that object can not be const.

jotik
  • 17,044
  • 13
  • 58
  • 123
  • It's worth noting what this leads to (i.e. you can output both const- and non-const nodes, but you can input only info a non-const node) – SingerOfTheFall Feb 15 '17 at 09:57
1
  • & Pass by reference. The argument passed in is the same as the object caller passing. No copy is occurred. It is needed if you need mutate some variable in function.

  • const Read-only. Any modification on this object causes compile error. It is a useful restrict to let compiler help you not accidentally modify it.

object to <<ostream is to read the passing argument to output to ostream. So it make sense to mark it as const. Marking & to avoid unnecessary copy.

istream>> to your obj. Read from istream to write your obj. So you must pass it as non-const reference to update some values on your passing object.

Chen OT
  • 3,486
  • 2
  • 24
  • 46
0

In the simplest way: const means that obj can't be changed.

The first function is overload of output operator. It only read the data of obj and writes it to output stream in some form.

The second function is overload of input operator. It reads from input stream into obj. Which means it alters obj. Therefore obj can't be marked const!

Victoriia
  • 105
  • 9