Link to home
Start Free TrialLog in
Avatar of Grant Rogers
Grant RogersFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Overloading the insertion operator

Hello, I have found something strange.  I am using Visual C++ 6.0 SP6 so I am not sure if it is a bug with this or what but here goes.

I wrote a small piece of code:
#include <iostream>

int main()
{
      const char *pMessage = "Hello World\n";
      std::cout.operator<<(pMessage);  // Prints out the address of pMessage
      std::cout << pMessage;               // Prints out the message

      return 0;
}

When I trace through the code the first call using cout matches the signature as const void * and the second one matches to  basic_ostream<_E, _Tr>& _O, const _E *_X in this case: basic_ostream<char, char_traits<char>>& _O, const char *_X as far as I am aware.

What I don't understand is why operator<<() is using a different signature from plain << I thought they are synonymous.  Can anyone tell me why?  Is it a bug to do with Microsofts C++ compiler?

Thanks
Grant
Avatar of beryl666
beryl666
Flag of United States of America image

yes. it return the refference of the pMessag only.
see:
http://www.edm2.com/0512/introcpp5.html
ASKER CERTIFIED SOLUTION
Avatar of beryl666
beryl666
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
std::operator<<(cout,pMessage); //your style
std::cout.operator<<(pMessage);  // this is only for character
 std::cout.operator<<(*(pMessage));  // this u will get character H

//please remember that the style to overload operator are not the same
for example
you want to overload
a++;
++B;
//prefix and postfix it has different style
// if i am not mistaken one is ++ operator() and another is operator()++

hope this clear
sorry is operator++()
Avatar of novitiate
novitiate

>>// if i am not mistaken one is ++ operator() and another is operator()++
A correction:

operator ++ () and operator ++ (int)

_novi_
ok thanks.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Grant Rogers

ASKER

Hi thanks for the info.  I now understand why my call was producing the result it did and how to retify this.
welcome :-)