Thread: Overloading compound operators?

  1. #1
    Registered User
    Join Date
    Apr 2004
    Posts
    210

    Overloading compound operators?

    I'm trying to overload several operators for a vector class I'm porting from C++ to C# (nothing serious, just playing around with C# to get some feeling for it).

    From the tutorials I read I learned that overloaded operators always have to be static. This is fine for stuff like +, -, *.... but what about += ?

    I read that C# will use the + operator here, but this means that the result of, say a+b, has to be stored in a temporary object which is then assigned to the variable on the left side of +=.

    The C++ class I'm porting uses a non-static operator and simply adds b to a's private fields (x,y,z) without returning anything. Is there anything similar I could do in C#? Or is this kind of optimization automatically done at compiletime?
    Last edited by Nyda; 04-27-2004 at 06:17 AM.

  2. #2
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,130
    To avoid C++ style confusion, operator overloading has some limitations in C#. You cannot overload the assignment operator. Likewise, you cannot overload any compund operator like += or -=. If you overload a binary operator, the associated compound operator will be overloaded for you.
    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

  3. #3
    Registered User
    Join Date
    Apr 2004
    Posts
    210
    Quote Originally Posted by nvoigt
    If you overload a binary operator, the associated compound operator will be overloaded for you.
    Seems like a big tradeoff to me, but then again, C# is all about safe, stable applications so it probably makes sense. Thanks for the reply.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Overloading operators
    By ugmusicbiz in forum C++ Programming
    Replies: 2
    Last Post: 02-13-2009, 01:41 PM
  2. Overloading fstream's << and >> operators
    By VirtualAce in forum C++ Programming
    Replies: 2
    Last Post: 04-09-2007, 03:17 AM
  3. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  4. operators overloading
    By waqasriazpk in forum C++ Programming
    Replies: 1
    Last Post: 07-26-2002, 01:05 AM
  5. Overloading operators...
    By Unregistered in forum C++ Programming
    Replies: 4
    Last Post: 11-21-2001, 08:24 PM