Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 7. More on Classes > Allocating and Returning Objects from Methods

Allocating and Returning Objects from Methods

We noted that the add: method changes the value of the object that is receiving the message. Let’s create a new version of add: that will instead make a new fraction to store the result of the addition. In this case, we need to return the new Fraction to the message sender. Here is the definition for the new add: method:

-(Fraction *) add: (Fraction *) f
{
   // To add two fractions:
   // a/b + c/d = ((a*d) + (b*c)) / (b * d)

   // result will store the result of the addition
   Fraction   *result = [[Fraction alloc] init];
   int        resultNum, resultDenom;

   resultNum = numerator * f.denominator +
       denominator * f.numerator;
   resultDenom = denominator * f.denominator;

   [result setTo: resultNum over: resultDenom];
   [result reduce];

   return result;
}


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint