Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why insertion operator is printing address instead of string?

I have simple lines of code, where I am using insertion operator << to show hello world string. If I use a operator b then it should result to a.operator(b); I try to do same thing with insertion operator and in output I got address of string, rather than actual string.

std::cout<<"Hello world"<<std::endl;
std::cout.operator<<("Hello world").operator<<(std::endl);

Output:

Hello world
0120CC74

I am using Visual Studio.

Does my operator conversion has any problem?

like image 291
Pranit Kothari Avatar asked Dec 16 '14 11:12

Pranit Kothari


People also ask

What does the insertion operator do?

The insertion ( << ) operator, which is preprogrammed for all standard C++ data types, sends bytes to an output stream object. Insertion operators work with predefined "manipulators," which are elements that change the default format of integer arguments.

Which of the following is called insertion operator in C++?

In C++, stream insertion operator “<<” is used for output and extraction operator “>>” is used for input.

How to overload<< cout?

To get cout to accept a Date object after the insertion operator, overload the insertion operator to recognize an ostream object on the left and a Date on the right. The overloaded << operator function must then be declared as a friend of class Date so it can access the private data within a Date object.


2 Answers

std::cout<<"Hello world"<<std::endl;

use overloaded output operator for const char*, that is free function, not member function.

std::cout.operator<<("Hello world").operator<<(std::endl);

use overloaded output operator for const void*, since const char* is implicitly convertible to const void*.

You can look at member overloads here and free overloads here

like image 120
ForEveR Avatar answered Nov 03 '22 06:11

ForEveR


My bet is that member function operator for std::ostream(char*) is not overloaded.

If you look at ostream::operator<<, void* is best match and char* naturally gets converted to it, while global operator<<(std::basic_ostream), has exact overloads for char* types, which gets picked up.

Of course, they behave differently.

like image 20
luk32 Avatar answered Nov 03 '22 06:11

luk32