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
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 9. Polymorphism, Dynamic Typing,... > Dynamic Binding and the id Type

Dynamic Binding and the id Type

Chapter 4 briefly touched on the id data type and noted that it is a generic object type. That is, id can be used for storing objects that belong to any class. The real power of this data type is exploited when it’s used this way to store different types of objects in a variable during the execution of a program. Study Program 9.2 and its associated output.

Program 9.2. Test Program main.m

// Illustrate Dynamic Typing and Binding


#import "Fraction.h"
#import "Complex.h"

int main (int argc, char *argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   id    dataValue;
   Fraction *f1 = [[Fraction alloc] init];
   Complex  *c1 = [[Complex alloc] init];

   [f1 setTo: 2 over: 5];
   [c1 setReal: 10.0 andImaginary: 2.5];

   // first dataValue gets a fraction

   dataValue = f1;
   [dataValue print];

   // now dataValue gets a complex number

   dataValue = c1;
   [dataValue print];

   [c1 release];
   [f1 release];

   [pool drain];
   return 0;
}

					  


  

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