Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are we allowed to chain together the insertion operator and other operators in general in C++?

Tags:

c++

operators

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 ?

like image 244
Mutating Algorithm Avatar asked Dec 19 '22 17:12

Mutating Algorithm


1 Answers

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.

like image 174
Joseph Mansfield Avatar answered Dec 22 '22 06:12

Joseph Mansfield