Jump to content
Larry Ullman's Book Forums

Operator Overloading - Script 9.5


Recommended Posts

Hi Larry,

 

I am having trouble getting my head around parts of this script. It works fine so no issues there - it's my lack of understanding that's the problem!

 

There are two main areas that I'm having trouble understanding - firstly the declaration and subsequent definition of the 'normalize()' method does not indicate that any values are provided to the method - therefore, is it correct to assume that the method 'knows' about the two object attributes - numerator and denominator?

 

Secondly, I do not understand the 'right hand side' parts of the overloading properly. Is it something like: when, say, the addition operator is invoked, it is passed two objects of type 'Rational', both of which have two attributes, a numerator and a denominator. So the rhs bits refer to the attributes of the second 'Rational' object passed to the addition operator?

 

Now to the subtraction, how does the addition operator know which two 'Rational' objects to add? (Point 5 on page 292).

 

Any clarifying thoughts will be most appreciated and thanks in anticipation.

 

Cheers from Oz.

Link to comment
Share on other sites

Sorry for the confusion here!
 

There are two main areas that I'm having trouble understanding - firstly the declaration and subsequent definition of the 'normalize()' method does not indicate that any values are provided to the method - therefore, is it correct to assume that the method 'knows' about the two object attributes - numerator and denominator?


The numerator and denominator are available to the function due to scope: because normalize() is called where those variables have scope. Admittedly, this isn't obvious!
 

Secondly, I do not understand the 'right hand side' parts of the overloading properly. Is it something like: when, say, the addition operator is invoked, it is passed two objects of type 'Rational', both of which have two attributes, a numerator and a denominator. So the rhs bits refer to the attributes of the second 'Rational' object passed to the addition operator?

Now to the subtraction, how does the addition operator know which two 'Rational' objects to add? (Point 5 on page 292).

 

Yes, the "right hand side" is the second Rational mentioned. And what we're doing is saying that f1 + f2 equates to calling the + method on the f1 object, passing f2 as an argument. 

 

For the subtraction, the subtraction method is being called on the left hand side Rational. So the invocation of the addition method calls the addition method of the same object (the left hand side Rational), passing the right hand side Rational as an argument.

 

Let me know if any of this is still unclear!

Link to comment
Share on other sites

 Share

×
×
  • Create New...