Thread: why can't << be overloaded as a member function

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    14

    why can't << be overloaded as a member function

    why can't << operator be overloaded as a member function is it because that is the way c++ is written and you just can't or is there another reason because I'm confused.

  2. #2
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    733
    It can, unless you want to provide an overload which has its left operand of a different type (e.g., std::ostream). The reason is that implementing it as a member implies that its left operand is of the same class type as the class which it is declared in.

  3. #3
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Another example is implementing a custom stream insertion operator for your own type. You obviously can't do that by declaring a operator<<() inside the definition of the stream -- you can't change that class, you don't own it.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing member variable as default arg to member function
    By Memloop in forum C++ Programming
    Replies: 1
    Last Post: 09-08-2009, 06:49 PM
  2. OverLoaded Member Function Not Found
    By lifeafterdeath in forum C++ Programming
    Replies: 2
    Last Post: 06-05-2008, 10:43 AM
  3. Why can = operator not be overloaded with member function?
    By chottachatri in forum C++ Programming
    Replies: 9
    Last Post: 02-22-2008, 04:30 PM
  4. Replies: 3
    Last Post: 07-23-2006, 01:09 PM
  5. private data member with public set member function
    By Mario in forum C++ Programming
    Replies: 2
    Last Post: 05-28-2002, 10:53 AM