Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding the operator<<() from std::cout

Tags:

c++

I have written this little code for one of my student coworker, in order to illustrate overloading in c++ :

#include <iostream>

int main() {
    std::cout << "Hello World!";
    std::cout.operator<<("Hello World!");
    return 0;
}

I thought naively I will have two times "Hello World!". But the second line send me an adress. I don't understand why ?

like image 535
Kafka Avatar asked Feb 19 '21 09:02

Kafka


2 Answers

According to cppreference (emphasis mine):

Character and character string arguments (e.g., of type char or const char*) are handled by the non-member overloads of operator<<. [...] Attempting to output a character string using the member function call syntax will call overload (7) and print the pointer value instead.

So in your case, calling the member operator<< will indeed print the pointer value, since std::cout does not have an overload for const char*.

Instead you can call the free function operator<< like this:

#include <iostream>
int main() {
    std::cout << "Hello World!";           //prints the string
    std::cout.operator<<("Hello World!");  //prints the pointer value
    operator<<(std::cout, "Hello World!"); //prints the string
    return 0;
}
like image 94
perivesta Avatar answered Oct 10 '22 01:10

perivesta


If an operator is a member function then

object operator other_operand

is equivalent to

object.operator(other_operand)

However, if the operator is not a member then it is rather

operator(object,other_operand)

Here you can find the list of overloads of << that are members https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt

And here the list of overloads that are non members https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2

Note that the operator<< for char* is not a member! But there is a member operator<< for void* that can print the value of a pointer of any type.

like image 44
463035818_is_not_a_number Avatar answered Oct 10 '22 03:10

463035818_is_not_a_number