Advertisement
Advanced C++, I/O Streams

How do you overload operator<< for a custom type?

Short answer

Define a free function operator<< taking std::ostream& and a const reference to your type, writing the members to the stream and returning the stream (to allow chaining). It's usually a non-member (often friend) so the stream is the left operand.

Save C++ mock interview
Advertisement
AModel answer
Define a free function operator<< taking std::ostream& and a const reference to your type, writing the members to the stream and returning the stream (to allow chaining). It's usually a non-member (often friend) so the stream is the left operand. This integrates your type with all output streams.
std::ostream& operator<<(std::ostream& os, const Point& p){
    return os << "(" << p.x << ", " << p.y << ")";
}
Real-world example
Overloading operator<< for a Point lets it be printed directly with std::cout like a built-in type.
Likely follow-ups
  • Why return the stream? | Why is it a non-member function?
Related topics