I have a totally basic C++ question here.
#include <iostream>
using namespace std;
int main() {
int a = 255;
cout << hex << a << endl; // <-----
}
In the code piece above, how is the std::cout statement chained?
I understand that an implementation of cout would return the reference to cout object to allow chaining to happen, so it should be executed as:
(((cout << hex) << a) << endl)
i.e. equivalent to these, in order
cout << hexcout << acout << endl
But this cannot be the case because somehow value of a needs to be converted to hex form!
How are operators actually chained by the compiler to make the conversion happen?
Here is how
hexis usually implemented:As you can see,
hexdoes not perform any conversion by itself: instead, it sets an option in the base stream to use hex for printing of numbers passed into it at a later point.EDIT (in response to a comment)
As hammar correctly notes, the other part of the puzzle is how
hex(ios_base& __base)is being called. There is an overload of the<<operator with this signature:This overload is essential implementation detail of stream manipulators. It is this overload that calls
hex, and lets it do its “magic” (which of course should not sound like magic to you any longer).