Obj-c method override/polymorphism problem

Posted by Rod on Stack Overflow See other posts from Stack Overflow or by Rod
Published on 2010-06-10T19:50:48Z Indexed on 2010/06/10 19:53 UTC
Read the original article Hit count: 121

Ok, so I'm using Objective-C. Now, say I have:

TopClass : NSObject
- (int) getVal {return 1;}
MidClass : TopClass
- (int) getVal {return 2;}
BotClass : MidClass
- (int) getVal {return 3;}

I then put objects of each type into an NSMutableArray and take one out. What I want to do is run the getVal func on the appropriate object type, but when I put

id a = [allObjects objectAtIndex:0];
if ([a isKindOfClass:[TopClass class]]) 
{
    int i;
    i = [a getVal];
}

I get firstly a warning about multiple methods called getVal (presumably because the compiler can't determine the actual object type until runtime). But more seriously I also get an error "void value not ignored as it should be" and it won't compile.

If I don't try and use the return from [a getVal] then it compiles fine e.g.

[a getval];  //obviously no good if I want to use the return value

It will also work if I use isMemberOfClass statements to cast the object to a class before running the function e.g.

if ([a isMemberOfClass:[BotClass]) i = [(BotClass*) a getVal];

But surely I shouldn't have to do this to get the functionality I require? Otherwise I'll have to put in a statement for every single subclass, and worse have to add a new line if I add a new sub class, which rather defeats the point of method overriding doesn't it?

Surely there is a better way?

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about polymorphism