Reputation: 2908
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.
Upvotes: 2
Views: 148
Reputation: 125007
A * a = [[B alloc] init]; // OK
B * b = [[A alloc] init]; // INCORRECT
Simply put, the first line is valid because any instance of B is necessarily an instance of A. It's therefore fine to assign a pointer to an instance of B to a variable of type A*
.
The second line is incorrect for a similar reason: instances of A are not necessarily instances of B, so it's not fine to assign a pointer to an instance of A to a variable of type B*
. More specifically, in the second line you're instantiating A directly, so the resulting object is definitely not an instance of B.
Think of it this way: it's correct to describe any square as a rectangle, but it's incorrect to say without extra information that a rectangle is a square.
Upvotes: 0
Reputation: 726809
If B
is a subclass of A
, its instances may be used everywhere where instances of A
could be used. The inverse is not true.
Here is a real-life example using Apple's classes: consider NSArray
and its subclass NSMutableArray
. Since NSMutableArray
is an NSArray
, the following assignment is valid:
NSArray *myArray = [[NSMutableArray alloc] init];
However, since NSArray
is not necessarily an NSMutableArray
, the following assignment is invalid:
NSMutableArray *myArray = [[NSArray alloc] init];
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 by A
, 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.
Upvotes: 3