← Samples

Overload operator<<

1234567891011121314151617#include <iostream> class foo { public: friend std::ostream& operator<<(std::ostream& stream, foo const& f); private: int x = 10; }; std::ostream& operator<<(std::ostream& stream, foo const& f) { return stream << "A foo with x = " << f.x; }

This sample is licensed under the CC0 Public Domain Dedication.


Write your class type objects to an output stream.


We implement operator<< on lines 13–17, which takes a reference to an std::ostream (the base class for all output streams) and the foo object we wish to write to the stream. On line 16, we simply write a string representing the foo object to the steam and return a reference to the stream itself, allowing this call to be chained.

Note that we declare this operator<< as a friend of foo on lines 6–7. This gives it access to foo’s private member, x.


  • Joseph Mansfield

Last Updated

05 April 2015


Fork this sample on GitHub