I come from a C# and Java background into C++ and I’m trying to get to understand the >> & << operators such as in
std::cout << "Hello World";
What I can’t understand in here is what the << operator is for. I tried declaring my own simple function that always returns the integer 5 and I can call it as I did in C#,
int x = MyFunction();
and that turns x into 5, but why do I need to use std::cout with <<? Also I would really appreciate it if you helped me understand what both >> and << are for.
Thanks to all of you for helping me understand this. What actually opened my mind is the fact that std::cout is and object 🙂
You didn’t spell it out exactly, but I believe that your confusion is that you think that
std::coutis a function, and you’re wondering why you don’t just call it like this:Well,
std::coutis not a function. The function in this statement isoperator<<.Or, more specifically, the function is
std::ostream::operator<<(const char*).The thing you need to understand is that operators are just functions with an alternative calling syntax.
operator<<is overloaded as a member function ofstd::ostream, andstd::coutis an object ofstd::ostream. So this:Is an alternative way to call this:
Note that
operator<<is a binary operator, which means it takes two arguments, if it’s declared as a free function, and one argument if it is declared as a member function. When you use the alternative calling syntax, the object on the left is the first argument, and the object on the right is the second argument. In the case where it is declared as a member function, as it is in this case, the object on the left is the calling object, and the object on the right is the argument.Here’s what it would look like if it were declared as a free function:
But, whether it is declared as a member or a free function, you can still use the same alternative calling syntax.