Thread: insertion operator

  1. #1
    Registered User
    Join Date
    May 2009

    insertion operator

    Consider the following code:

    #include <iostream>
    int main()
    	using namespace std;
    	cout << 'a' << endl << 'b' << endl;
    	cout.operator <<('a');
    	cout << endl;
    	cout.operator <<('b');
    	cout << endl;
    	cout.operator <<(*"ab");
    	cout << endl;
    	cout.operator <<("ac");
    	cout << endl;
    	operator <<(cout, "ac");
    	cout << endl;
    	return 0;
    The output looks like this:

    where the '00B57800' is just some memory location. That's also the line that surprized me. I was expecting to see 'ac' there because I had thought that 'cout << "ac";' was just shorthand for 'cout.operator <<("ac");'
    Since that's obviously not the case, I looked around in Stroustrup 2009 and found on p. 610:
    basic_ostream& operator<<(const void* p)
    So, that explains the output of a memory location, and one of the template classes further down on the same page explains why operator <<(cout, "ac"); does give the desired 'ac' output.

    What I'm wondering, though, is how the compiler knows to interpret 'cout << "ac";' as 'operator <<(cout, "ac");' rather than as 'cout.operator <<("ac");'

  2. #2
    Registered User
    Join Date
    Nov 2007
    I believe it does so through ADL

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. why can't my perceptron learn correctly?
    By yann in forum C Programming
    Replies: 25
    Last Post: 10-15-2010, 12:26 AM
  2. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 07:05 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  5. operator overloading and dynamic memory program
    By jlmac2001 in forum C++ Programming
    Replies: 3
    Last Post: 04-06-2003, 11:51 PM