C++
Stream operators
Learn to overload << and >> operators.
Stream operators
operator<< and operator>> let you write an object to a stream and read from a stream. These operators are defined as global functions, not as members of the class.
Example: std::ostream& operator<<(std::ostream& os, const Point& p) { os << p.x << " " << p.y; return os; }. This lets you write std::cout << p;. The function returns std::ostream&; this enables chaining (std::cout << a << b). Why global? Because the left side is not your class but std::ostream. A member operator would need to be added inside std::ostream, which is not possible.
Chaining and return os
The operator<< function returns the stream with return os;. This lets you write multiple objects in sequence.
Example: std::cout << a << " " << b; works like this: first operator<<(std::cout, a) is called and returns std::cout. Then " " is written to the returned stream and the stream is returned again. Finally b is written. If the function returned void, chaining would not work; std::cout << a << b would be a compile error. That is why return os; is mandatory.
Exercise Add operator<< for Point
Add a global operator<< function for the Point class in the starting code: std::ostream& operator<<(std::ostream& os, const Point& p) { os << p.x << " " << p.y; return os; }. In main print the point with std::cout << p;.
Show example solution
#include <iostream>
class Point {
public:
int x;
int y;
Point(int x_, int y_) : x(x_), y(y_) {}
};
std::ostream& operator<<(std::ostream& os, const Point& p) {
os << p.x << " " << p.y;
return os;
}
int main() {
Point p(3, 7);
std::cout << p;
return 0;
}
Test yourself
-
Stream operator signature
std::ostream& ____(std::ostream& os, const Point& p) { os << p.x; return os; }
Show answer
std::ostream& operator<<(std::ostream& os, const Point& p) { os << p.x; return os; }
-
Match each piece to its role
- operator<<
- Writing to output stream
- operator>>
- Reading from input stream
- std::ostream&
- Return type
- return os
- Returning the stream
-
Why is operator<< defined as a global function?
std::ostream& operator<<(std::ostream& os, const Point& p);
- Because it is faster
- Because the compiler requires it
- Because it cannot be written inside the class
- Because the left side is std::ostream
Show answer
Because the left side is std::ostream — The left side is not your class but std::ostream.
Next lesson: Spaceship operator