skip to content

How do you write operator<< and operator>> for a C++ Interval type so it can be printed and parsed with streams?

level: middleimportance: should knowfreq 55%

answer

  1. the stream is the left operand
  2. return the stream by reference
  3. a friend declared inside the class
  4. commit only on success
  5. report failure through the state

basics

~20 s

Write them as non-member functions taking the stream by reference and returning it: operator<< takes the Interval by const reference, operator>> by non-const reference. The input operator assigns only after a fully successful read and sets failbit on bad input.

solid answer

~40 s

Because the stream is the left operand, these operators cannot be members of `Interval`; they are non-member functions, usually declared as `friend`s inside the class so they can reach private members and are found by argument-dependent lookup. `std::ostream& operator<<(std::ostream& os, const Interval& r)` writes the pieces with `os << ...` and returns `os`, so calls chain. `std::istream& operator>>(std::istream& is, Interval& r)` reads into local variables, checks both the stream and the value's own rules, assigns to `r` only if everything succeeded, and otherwise calls `is.setstate(std::ios_base::failbit)` so the caller's `while (in >> r)` loop stops. Returning the stream by reference is what makes chaining and the `if (in >> r)` test work. Avoid `std::endl` and sticky manipulators inside `operator<<`; leave flushing and formatting state to the caller.

code

cpp · 27 lines
cpp
#include <iostream>
#include <sstream>

struct Interval {
    int lo = 0, hi = 0;

    friend std::ostream& operator<<(std::ostream& os, const Interval& r) {
        return os << '[' << r.lo << ", " << r.hi << ']';
    }
    friend std::istream& operator>>(std::istream& is, Interval& r) {
        int lo, hi;
        char dash;
        if (is >> lo >> dash >> hi && dash == '-' && lo <= hi) {
            r = {lo, hi};                       // commit only on success
        } else {
            is.setstate(std::ios_base::failbit);
        }
        return is;
    }
};

int main() {
    std::istringstream in("3-7 10-12 9-2");
    Interval r;
    while (in >> r) std::cout << r << '\n';
    std::cout << "stopped, last good value " << r << ", fail=" << in.fail() << '\n';
}

go deeper

for a junior

Recall the two signatures: stream by reference in, stream by reference out, and the value as const reference for output.

for a middle

Explain why the operators are non-members, why returning the stream enables chaining, and how failbit signals bad input.

for a senior

Show an input operator that validates, commits only on success, honours exceptions() through setstate, and leaves no sticky formatting state.

for a principal

Decide which domain types get stream operators at all, and whether their text formats must round-trip or are display-only.

## Why they are non-member functions An expression `std::cout << r` calls `operator<<` with the **stream on the left** and the `Interval` on the right. A member function always takes its own class as the left operand, so `operator<<` as a member of `Interval` would have to be called as `r << std::cout`, which nobody wants. Both stream operators are therefore **non-member** functions: ```cpp std::ostream& operator<<(std::ostream& os, const Interval& r); std::istream& operator>>(std::istream& is, Interval& r); ``` The usual way to write them is as `friend` functions defined inside the class. They then reach private members, and they are found by argument-dependent lookup when an `Interval` is involved, without cluttering the enclosing namespace. Lookup rules for such friends are covered with namespaces and argument-dependent lookup. ## The output operator ```cpp friend std::ostream& operator<<(std::ostream& os, const Interval& r) { return os << '[' << r.lo << ", " << r.hi << ']'; } ``` Points worth saying: - Take the value by **`const` reference**: printing must not copy or modify it. - **Return the stream** by reference so `std::cout << a << ' ' << b` chains, since each `<<` returns the stream for the next. - **Do not flush or end the line.** No `std::endl`, no `'\n'`: the caller decides layout. - **Do not leave sticky state behind.** Manipulators such as `std::hex` or `std::setprecision` stay on the stream after your operator returns; if you must use one, restore the previous flags. - Write to `os`, never to `std::cout`, so the same operator works for files and `std::ostringstream`. ## The input operator The input side is where candidates show depth. A tool that reads ranges such as `3-7` might write: ```cpp friend std::istream& operator>>(std::istream& is, Interval& r) { int lo, hi; char dash; if (is >> lo >> dash >> hi && dash == '-' && lo <= hi) { r = {lo, hi}; // commit only on success } else { is.setstate(std::ios_base::failbit); } return is; } ``` 1. **Read into locals.** If the read fails halfway, the caller's object keeps its old value instead of a half-updated one. 2. **Validate the value's own rules.** The stream cannot know that `lo <= hi`; `9-2` parses as two integers but is not a valid `Interval`. 3. **Report failure through the stream.** `is.setstate(std::ios_base::failbit)` is the stream's error channel, so `while (in >> r)` stops exactly as it does for a bad `int`. It also respects the stream's `exceptions()` mask: if the caller asked for exceptions, `setstate` throws. 4. **Return the stream** so the caller can test it and chain reads. ## How it behaves Reading `3-7 10-12 9-2` from a `std::istringstream` in a `while (in >> r)` loop prints `[3, 7]` and `[10, 12]`, then stops. After the loop `r` still holds `[10, 12]`, because the operator never assigned the invalid `9-2`, and `in.fail()` is true. | Design choice | Good | Weak | |---|---|---| | Placement | `friend` defined in the class, or a free function in the same namespace | member function | | Output parameter | `const Interval&` | by value | | Return | the stream by reference | `void` or a copy | | Input failure | `setstate(failbit)`, object unchanged | partly assigned object, error printed to `std::cerr` | | Layout | no newline, no flush | `std::endl` inside the operator | ## Round-tripping If the output and input formats differ, as here (`[3, 7]` out, `3-7` in), a value written by `operator<<` cannot be read back by `operator>>`. For data that is saved and reloaded, make the two symmetric and test the round trip; for display-only output, document that the format is not meant to be parsed. ## Testing the operators String streams make both operators easy to unit-test without files or a console: write an `Interval` into a `std::ostringstream` and compare `str()` with the expected text, and read from a `std::istringstream` holding good input, bad separators, a reversed range and an empty string. For each bad case, check that `fail()` is true **and** that the target object still holds its previous value. ## Common mistakes - Declaring `operator<<` as a member and wondering why `std::cout << r` does not compile. - Returning `void`, which breaks `std::cout << r << '\n'`. - Throwing a custom exception or printing an error from `operator>>` instead of setting `failbit`. - Assigning `r.lo` before discovering that `hi` is missing, leaving a half-updated object.

  • Why call is.setstate(std::ios_base::failbit) instead of throwing from operator>>?
    Callers of stream extraction expect failure to show up in the stream state, so `while (in >> r)` and `if (in >> r)` work for your type as for `int`. `setstate` also honours the stream's `exceptions()` mask, so a caller who asked for exceptions still gets `std::ios_base::failure`.
  • What is wrong with writing std::endl at the end of operator<<?
    It forces a newline and a flush on every caller. Someone printing two intervals on one line, or writing thousands to a file, cannot undo either. An output operator should write only the value and leave line breaks, flushing and other layout to the caller.

  • operator<< should be a member function of the class it prints
  • operator>> should print an error message when the input is bad
  • The input operator can assign members as it reads them
  • operator<< can return void because the stream is a reference anyway
  • Ending operator<< with std::endl makes the type easier to use