Thread: overload

  1. #1
    Unregistered
    Guest

    overload

    Has anyone ever heard of overloading an '+' operator and make it do subtraction.

    Scott V.

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    It can be done but it is probably not a good idea. The closest useful example of something similar is in the stl with reverse iterators whereby operator ++ applied to the iterator will actually move you backwards through the container.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    Hmm...If I were you, I would just create two different statements, rather than try to overload '+'.
    What will people say if they hear that I'm a Jesus freak?
    What will people do if they find that it's true?
    I don't really care if they label me a Jesus freak, there is no disguising the truth!

    Jesus Freak, D.C. Talk

    -gnu-ehacks

  4. #4
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    It is a good practice to overload operators relative to their original function. If + adds in its original form then your overloaded version should be a derivative of adding not subtracting. Otherwise, your code will get very confusing very fast especially with classes. If you overload + to subtract relative to a class then:

    No overload here:

    int y=10;
    int x=20;
    int sum=x+y; //Adds

    Overloaded + relative to Vector class.

    Vector Vec1;
    Vector Vec2;
    Vector Sum=Vec1+Vec2; //Subtracts


    As you can see it is not apparent from the code which version subtracts and which one adds. This is why the + relative to Vector should add and not subtract. It gives continuity and consistency to your operators.

    Just because C++ gives us the power to abuse the operators
    does not mean that we should. Imagine if someone else were to try to read your code and you had done this.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. overload *
    By shuo in forum C++ Programming
    Replies: 5
    Last Post: 06-10-2007, 04:44 AM
  2. Overload Operators
    By verbity in forum C++ Programming
    Replies: 3
    Last Post: 03-25-2007, 11:13 AM
  3. Having trouble with operator*=()
    By Lurker in forum C++ Programming
    Replies: 10
    Last Post: 10-26-2003, 03:03 PM
  4. C++ Operator Overload Question
    By cworld in forum C++ Programming
    Replies: 0
    Last Post: 03-25-2002, 07:17 PM
  5. Overload (+) operator
    By kit in forum C++ Programming
    Replies: 8
    Last Post: 10-23-2001, 11:20 AM