Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the << operator doing in C++?

In the example below, what exactally is the << operator doing? I'm guessing it is not a bitwise operator.

std::cout << "Mouse down @ " << event.getPos() << std::endl;

I understand what the code will do here: Use standard out, send this text, send an end of line. Just I've never come accross the use of this << apart from on raw binary.

I'm starting out with C++. And, as an operator of sorts, it's hard to search for a description of this and what it means. Can someone enlighten me and/or give me a pointer as to what to google for?

Thanks Ross

like image 449
Ross Avatar asked Jul 24 '10 14:07

Ross


People also ask

What does the << operator do?

Description. This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.

What is the output of left shift operator << on?

Explanation: Left Shift Operator << shifts bits on the left side and fills Zeroes on the Right end.

What is the use of << and >> in C++?

Left Shift and Right Shift Operators in C/C++ Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.


2 Answers

The answer is: The << operator does left shifts by default for integral types, but it can be overloaded to do whatever you want it to!

This syntax for piping strings into a stream was first (I think) demonstrated in C++ inventor Bjarne Stroustroup's eponymous book The C++ Programming Language. Personally, I feel that redefining an operator to do IO is gimmicky; it makes for cool-looking demo code but doesn't contribute to making code understandable. Operator overloading as a technique has been widely criticized in the programming language community.


EDIT: Since nobody else has mentioned this yet:

operator<< is defined in the ostream class, of which cout is an instance. The class definition sits in the iostream library, which is #include'd as <iostream>.

like image 92
Carl Smotricz Avatar answered Oct 12 '22 22:10

Carl Smotricz


The operator<< is being overloaded. Check out Operator Overloading.

like image 44
Siqi Lin Avatar answered Oct 12 '22 23:10

Siqi Lin