insertion operator

This is a discussion on insertion operator within the C++ Programming forums, part of the General Programming Boards category; Consider the following code: Code: #include <iostream> int main() { using namespace std; cout << 'a' << endl << 'b' ...

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    242

    insertion operator

    Consider the following code:

    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:
    a
    b
    97
    98
    97
    00B57800
    ac

    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
    Posts
    46
    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, 01:26 AM
  2. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 08:05 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 03:39 PM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 04:00 PM
  5. operator overloading and dynamic memory program
    By jlmac2001 in forum C++ Programming
    Replies: 3
    Last Post: 04-07-2003, 12:51 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21