Operator overloading is a feature in C++ that allows developers to redefine the way operators work with user-defined types (classes). The insertion operator (<<) is commonly used for outputting content to streams like
std::cout
, but by default, it doesn't know how to handle custom types.
Overloading the << operator for your class means that you're providing a way to represent your object as a stream of characters. This custom behavior is applied when you use the operator to insert an object of your class into an
std::ostream
.
To overload the << operator for a custom class
Length
, the following declaration is made a friend within the class:
friend std::ostream& operator<<(std::ostream& os, const Length& length);
Defining how the operator works lets you elegantly output
Length
objects, for instance, by showing the length measurement in meters and centimeters.