I'm trying to understand the underlying process in C++ that allows us to form the following expression in C++:
cout << "Hello," << "World" << a + b;
From my understanding, first, the insertion operator takes the ostream object cout
and the string literal "Hello"
as operands and the expression returns a type of cout
and thus cout
is now the type of the next string literal and finally also the type of the expression a + b
.
I'm having trouble understanding the technical details of this process, I understand references are involved which allow us to do this ?
From my understanding, first, the insertion operator takes the ostream object cout and the string literal "Hello" as operands and the expression returns a type of cout...
Good so far...
and thus cout is now the type of the next string literal and finally also the type of the expression a + b.
I'm not sure what you're trying to say here. Maybe it'll help if the operators are grouped according to precedence:
(((cout << "Hello,") << "World") << (a + b));
The first time operator<<
is called, its arguments are cout
and "Hello"
, as you said. That returns cout
. Then, the second time, the arguments are cout
(the result of the previous one) and "World"
. Then, the third time, the arguments are cout
and the result of a + b
.
Maybe it will help further to rewrite the code using the (technically incorrect, see @DavidRodríguez-dribeas's comment) function call syntax:
operator<<(operator<<(operator<<(cout, "Hello,"), "World"), a + b);
Because each time operator<<
is called it returns cout
, the first argument of each call will be cout
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With