Created
March 2, 2012 10:29
-
-
Save pratikshabhisikar/1957579 to your computer and use it in GitHub Desktop.
Converting Base Pointer to Derived Pointer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NSString *base = [[NSString alloc] initWithString:@"Base"]; | |
NSLog(@"Base pointer is instantiated with type: %@", [base class]); | |
// NSMutableString is derived from NSString class. | |
NSMutableString *derived = [NSMutableString stringWithString:@"Derived"]; | |
NSLog(@"Derived pointer is instantiated with type: %@", [derived class]); | |
// Converting Base to Derived:- | |
base = derived; | |
/* No error or warnings. This is implicit conversion from a pointer to base TO pointer to derived. | |
We know a derived object contains base part + it's own part, let's say - derived part. | |
Since base part is also present in the derived part, it is safe to convert base pointer to derived. | |
The base pointer now actually is made to point to the base part of the derived object. | |
*/ | |
NSLog(@"Base Pointer is now of type: %@", [base class]); | |
NSLog(@"%d", base.length); // -length is a method present in NSString class. It continues to access the base part. | |
// [base appendString:@"I can't access the derived part"]; // Error. Trying to access derived part -appendString: | |
[(NSMutableString *)base appendString: @"I can forcefully access the derived part"]; | |
NSLog(@"%@", base); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment