<<
is a binary operator in C++, and thus can be overloaded.
You know of the C usage of this operator, where 1 << 3
is a binary operation returning 8
. You could think of this as the method int operator<<(int, int)
where passing in arguments 1
and 3
returns 8
.
Technically, operator<<
could do anything. It's just an arbitrary method call.
By convention in C++, the <<
operator is used for handling streams in addition to being the bit-shift operator. When you perform cout << "Hello!"
, you are calling a method with prototype ostream & operator<< (ostream & output, char const * stream_me)
. Note the return value ostream &
. That return allows you to call the method multiple times, like std::cout << "Hello World" << "!";
which is calling operator<<
twice... once on std::cout and "Hello World", and the second time on the result of that first invocation and "!".
In general, if you were to create a class named class Foo
, and you wanted it to be printable, you could define your printing method as ostream & operator<< (ostream & output, Foo const & print_me)
. Here is a simple example.
#include <iostream>
struct Circle {
float x, y;
float radius;
};
std::ostream & operator<< (std::ostream & output, Circle const & print_me) {
output << "A circle at (" << print_me.x << ", " << print_me.y << ") with radius " << print_me.radius << ".";
}
int main (void) {
Circle my_circle;
my_circle.x = 5;
my_circle.y = 10;
my_circle.radius = 20;
std::cout << my_circle << '\n';
return 0;
}