Subclassing a class – assign from broad to narrow

Some notes that help when subclassing a class and can’t remember how things work:

Assign from broad to narrow works however from narrow to broad is usually an error.For example, an Animal is broad – it’s very generic. However, a Cow is very narrow – it has a very specific definition.

Here’s an example:

Cow *cow = [Animal alloc] init];

is OK as a cow can respond to all Animal messages.

However,

Animal *animal = [[Cow alloc] init];

is NOT ‘cos animal cannot respond to Cow messages (such as moo) and will crash.

So, it’s OK to assign from broad to narrow:

Cow *cow = animal;

but not narrow to broad:

Animal *animal = cow; // bad – will crash

One note:  id is special. It’s OK to assign to it in both broad and narrow cases.

So, to summarise:

broad to narrow: OK
narrow to broad: usually an error

And, if you’re going to use id, use Introspection or Protocols.

Leave a Reply

Your email address will not be published. Required fields are marked *