Why does calling cout.operator<<(const char*) print the address instead of the character string?

When you do cout.operator<<(str) you call cout's operator << member function. If we look at what member functions overloads cout has we have

basic_ostream& operator<<( short value );
basic_ostream& operator<<( unsigned short value );

basic_ostream& operator<<( int value );
basic_ostream& operator<<( unsigned int value );

basic_ostream& operator<<( long value );
basic_ostream& operator<<( unsigned long value );

basic_ostream& operator<<( long long value );
basic_ostream& operator<<( unsigned long long value );

basic_ostream& operator<<( float value );
basic_ostream& operator<<( double value );
basic_ostream& operator<<( long double value );

basic_ostream& operator<<( bool value );

basic_ostream& operator<<( const void* value );

basic_ostream& operator<<( std::nullptr_t );

basic_ostream& operator<<( std::basic_streambuf<CharT, Traits>* sb);

basic_ostream& operator<<(
    std::ios_base& (*func)(std::ios_base&) );

basic_ostream& operator<<(
    std::basic_ios<CharT,Traits>& (*func)(std::basic_ios<CharT,Traits>&) );

basic_ostream& operator<<(
    std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) );

If you notice, there isn't one for a const char*, but there is one for a const void*. So, your const char* is converted to a const void* and that version of the function prints the address held by the pointer.

What you need to do is call the non member function overload of operator<< and to do that you can use

cout << str;

The problem is that for some types operator<< is overloaded as a member of ostream and for some types it is overloaded as a global function. In the case of const char* it's a global function, so if you want to call the operator function explicitly you must write

operator<<(cout, str);

but for integer types you must write

cout.operator<<(num);

What's happening in the code you posted is that the overload for const void* is being called, which is why you see hexadecimal numbers.

Tags:

C++

C++11

C++14