Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In c++ what happens, if both objects overload operator<<? a<<b

I thought that in

cout << "Hello world" 

cout object has an operator overloading so we can pass strings into cout objects member function.

But in some example code I saw a class which has an operator overloading defined in it.

class GenericPlayer : public Hand
{
    ..
    friend ostream& operator <<(ostream& os, const GenericPlayer& aGenericPlayer);
    ..
};

...
cout << aGenericPlayer << endl;
...

Even if it is not, what if both cout and aGenericPlayer overload operator<< ?

like image 917
Engin Bulanık Avatar asked Dec 15 '22 16:12

Engin Bulanık


2 Answers

Even if it is not, what if both cout and aGenericPlayer overload operator<< ?

std::cout is an std::ostream object, so any std::ostream& operator<<(std::ostream, SomeType) will work with std::cout. But the point is that the second parameter of the operator is different, so the overloads are different. The first "string" one is something like

std::ostream& operator<<(std::ostream&, const char*);

and the second

std::ostream& operator <<(std::ostream& os, const GenericPlayer& aGenericPlayer); 

So, they are different operator overloads and there is no ambiguity.

like image 130
juanchopanza Avatar answered Jan 08 '23 06:01

juanchopanza


First, neither cout nor aGenericPlayer can overload anything. They're objects, and overloading is based on types (even if you wouldn't normally says that type X overloads <<, but rather that there is an overload of << which can take a type X as its second argument).

Second, overload resolution is based on all of the arguments, not just one. There are something around twenty different overloads of << for std::istream (which is a base class of the type of std::cout), but none (at least in the standard library) take a GenericPlayer as second parameter. So they can't be used if the second operand isn't a GenericPlayer. Similarly, you could have an operator<<( int, GenericPlayer const& ), in addition to the one you have; it would be called if the left hand side had type int, and the right hand side type GenericPlayer. (I can't think of any case where this wouldn't be operator overloading abuse, but the language certainly allows it.)

like image 21
James Kanze Avatar answered Jan 08 '23 05:01

James Kanze