Here is the code
#include<iostream>
using namespace std;
main()
{
cout<<"Hellow World"<<endl;
cout.operator<<("Hellow World");
cout.operator<<(endl);
}
I know that cout<<"Hellow World"<<endl;
is interpreted as
cout.operator<<("Hellow World");
But this code is producing the following results
Hellow World
0x8048830
if i use operator<<(cout,"Hellow World");
works fine
what is the difference between cout.operator<<("Hellow World");
and
operator<<(cout,"Hellow World");
std::basic_ostream
overloads operator<<
in two groups, members and non-members.
The difference is due to the fact that when you write cout<<"Hellow World"<<endl;
the non-member overload of const char*
is chosen to print the string literal.
When you call the member version, the best fit is only the void*
overload.
what is the difference between
cout.operator<<("Hellow World");
andoperator<<(cout, "Hellow World")
;
When you write cout.operator<<("Hellow World");
you are calling the operator<<
method and passing a const char *
. Because this method is not overloaded to take a const char *
, but is overloaded to take a const void *
, that's the one you call and get 0x8048830
(which is the address of the 'H'
character in your string).
When you write operator<<(cout, "Hellow World")
you are calling a free function operator<<
that takes an output stream on the left-hand side and a const char *
on the right-hand side. There happens to exist such a function, and it has the following declaration (simplified):
std::ostream& operator<<(std::ostream& os, const char *s);
And so you get printed the sequence of characters that begin at s
, and end at the first '\0'
that is encountered (so you get Hellow, world
).
Finally, when you write std::cout << "Hello, world" << std::endl;
, since you are passing a const char *
to operator<<
, the free function, being a perfect match, is chosen over the method operator<<
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With