cout << "hello"; vs cout.operator<<("hello");

The former displays hello while the latter displays an address.

Could someone help me understand why?
Unverified, educated guess:

cout.opeartor <<("hello"); calls the member function (taking a void* as a param). using the '.' operator implies that the operator must be a member of 'cout'.

cout << "hello"; calls the appropriate overload. In this case it calls the expected const char* version which prints a string. This overload probably isn't a member, but rather is a friend function.
Thank you so much Disch. This was so weird to me.

I wrote a toy program to try it out.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

class fooClass
{
public:
	fooClass& operator<<(void* test)
	{
		std::cout << test << std::endl;
		return *this;
	}
	friend fooClass& operator<<(fooClass&, char*);

} foo;

fooClass& operator<<(fooClass& obj, char* str)
{
	std::cout << str << std::endl;
	return obj;
}

int main(int argc, char* argv[])
{
	foo << "test"; // displays test
	foo.operator<<("test2"); // displays the address of test2

	return 0;
}

Topic archived. No new replies allowed.