Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insertion operator not producing the expected output?

Tags:

c++

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");

like image 714
Anjaneyulu Avatar asked Jan 01 '17 09:01

Anjaneyulu


2 Answers

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.

like image 56
StoryTeller - Unslander Monica Avatar answered Nov 09 '22 16:11

StoryTeller - Unslander Monica


what is the difference between cout.operator<<("Hellow World"); and operator<<(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<<.

like image 30
cute_ptr Avatar answered Nov 09 '22 15:11

cute_ptr