B is a subclass of class A.
A * a = [[B alloc] init];
B * b = [[A alloc] init];
Which of these is invalid and why?
When I typed this in I got a warning for the second thing, but I couldn’t understand what it meant. It showed “Incompatible pointer types initializing ‘B * __strong’ with an expression of type ‘A *'”. Also may some one tell me if the second expression can be made valid or not and how to do the same.
If
Bis a subclass ofA, its instances may be used everywhere where instances ofAcould be used. The inverse is not true.Here is a real-life example using Apple’s classes: consider
NSArrayand its subclassNSMutableArray. SinceNSMutableArrayis anNSArray, the following assignment is valid:However, since
NSArrayis not necessarily anNSMutableArray, the following assignment is invalid:EDIT From the language point of view, both assignments are valid: the code is going to compile, and may even run if you steer clear of
B‘s methods not also supported byA, thanks to the dynamic method dispatch mechanism of Objective C. But the compiler can no longer validate the code that involves the variable, and tell you of other potential problems.