Misunderstanding about ostream class and operator <<

c++, iostream

Solution

The first group of operators are members of the stream class.

Most operator overloads, like those in the second group, are not.

As to the why, it is likely just a historical accident. The operators for built in types can be added to the stream classes, and obviously they were (long before C++ was standardized). The standard just documents existing practice here.

Operators for user defined types obviously cannot be added to the stream classes, so they are implemented as free functions.

In retrospect it would have been more consistent to make all the operators free functions, but that would possibly break some old programs.

Problem

After looking at the `ostream::operator <<` c++ reference, I noticed the following declarations: ``` ostream& operator<< (bool val); ostream& operator<< (short val); ostream& operator<< (unsigned short val); ostream& operator<< (int val); ostream& operator<< (unsigned int val); ostream& operator<< (long val); ostream& operator<< (unsigned long val); ostream& operator<< (float val); ostream& operator<< (double val); ostream& operator<< (long double val); ostream& operator<< (void* val); ostream& operator<< (streambuf* sb ); ostream& operator<< (ostream& (*pf)(ostream&)); ostream& operator<< (ios& (*pf)(ios&)); ostream& operator<< (ios_base& (*pf)(ios_base&)); ``` But then I found out that there are also the following declarations: ``` ostream& operator<< (ostream& os, char c); ostream& operator<< (ostream& os, signed char c); ostream& operator<< (ostream& os, unsigned char c); ostream& operator<< (ostream& os, const char* s); ostream& operator<< (ostream& os, const signed char* s); ostream& operator<< (ostream& os, const unsigned char* s); ``` Why are the char/string output operators not member functions?

Original source