Results 1 to 5 of 5

Thread: plus(+) operator

Threaded View

  1. #4
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: plus(+) operator

    Operator overloading should follow the following syntax:

    Code:
    	 MyClass operator+(const SomeOtherClass &value)
    	 {
    		 MyClass result;
                     // calculate new values for result based on the addition of this instance and 'value'
                     return result;
    	 }
    It sounds to me like you are wanting to modify the instance itself inside the + operator overload. I would strongly advice against that. It would mean that this addition:
    Code:
    Student myStudent;
    myStudent.feespaid = 0;
    myStudent + 5.0;
    Would actually alter the "myStudent" instance. An addition between two operands should not modify the operands, that is, they should stay the same after the addition has taken place.
    So, if anything, what you really want to overload is the += operator:

    Code:
    	 Student& operator+=(const float value)
    	 {
    		 this->feespaid += value;
    		 return *this;
    	 }
    Altough I feel that an addition between a Student and a float is abit illogical, atleast now it doesnt violate the "rules" of addition
    Last edited by Atheist; Nov 4th, 2012 at 06:42 AM.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width