Program Challange

The below program executed successfully. but I have a confusion how it will works. Can anyone explain the program execution.


#include <iostream>

int main ()
{
std::cout.operator<<("Hello world"); // How this link works
return 0;
}

I understood the execution of the program but still i have confusion for output of that program.

the program output is 0x400844
Last edited on
std::cout is an object.
operator<<() is effectively a member function of that object.

So this code is calling a member function of an object.
When you write:
 
std::cout << "Hello world";

the compiler looks at the definition of instance std::cout and to determine its type. It then looks at that object to see if it has a member function operator<<(const char*) and uses it.

So that code, runs the function call:
 
std::cout.operator<<("Hello world");

The symbol operator<< is just the name of a function, but matches << in your code.

Why bother with all that when you could already write to stdout with printf("%s", "Hello world")? You can't create custom format specifiers for your special new class that printf will recognise, so a new system was required that worked with built in types, int long double and so on, and also works with any type that someone would create in the future. It is was made generic enough to work with any stream (serial i/o thing).
Last edited on
Topic archived. No new replies allowed.