0Pricing
C++ Academy · Lesson

Stream Insertion and Extraction Operators

Teach your types to interoperate with std::cout via >.

Why Overload << and >>

Teach your types to interoperate with std::cout and std::cin by overloading the stream operators.

The Insertion Operator <<

Define as a free function taking an output stream by reference. Return the stream to enable chaining.

struct Point { int x, y; };

std::ostream& operator<<(std::ostream& os, const Point& p) {
    return os << "(" << p.x << ", " << p.y << ")";
}

Point p{3, 4};
std::cout << p << "\n";   // (3, 4)

All lessons in this course

  1. Arithmetic and Comparison Operators
  2. Stream Insertion and Extraction Operators
  3. Subscript and Function Call Operators
  4. Three-Way Comparison Operator C++20
← Back to C++ Academy