Inheritance question for chapter challenge


#1

I read in chapter 18 (page 111) that you can use a base class in place of an inherited class from said base class because the inherited class contains everything that the base class has and more… but I am running into the following problem, and was wondering if anybody could clear up what is going on for me… Thanks in advance!

My addStock method that receives a ForeignStockHolding and adds it to an NSMutableArray looks like this:

- (void)addStock:(ForeignStockHolding *)s
{
   if (!stockHoldings) { 
      // Create the array
      stockHoldings = [[NSMutableArray alloc] init];
   }
   [stockHoldings addObject:s];

When I try to send a pointer to a StockHolding class instance (not ForeignStockHolding) with this code:

StockHolding *holding1 = [[StockHolding alloc] init];
// set the instance values of class
...
...
[stockPortfolio addStock];

I get the following warning:
"Incompatible pointer types sending ‘StockHolding * __strong’ to paramater of type ‘ForeignStockHolding *’ :frowning:

Now, I understand that the warning is basically saying “hey, you are trying to pass a pointer to an instance of StockHolding to a method that expects a pointer to an instance of ForeignStockHolding”, but the code does then go on to work…

My question I guess, is how would you create a method that accepts any flavour of StockHolding, be it StockHolding or ForeignStockHolding or even MartianMarketStockHolding?

I know in C# I would have just created a couple overwritten functions like addStock(ForeignStockHolding stockHolding) and addStock(StockHolding stockHolding) …etc, but I’m pretty sure I read somewhere that Objective-C doesn’t support overwritten methods?

Thanks again for any insight anybody can give me,
Really enjoying this book - never thought I’d get a handle on the language as quickly as the book is allowing me to!


#2

- (void)addStock:([color=#FF0000]ForeignStockHolding[/color] *) should be - (void)addStock:([color=#008000]StockHolding[/color] *)

@interface StockHolding: NSObject
...
@end

@interface ForeignStockHolding: StockHolding
...
@end

An instance of ForeignStockHolding can behave like a StockHolding instance but not vice versa.


#3

Thank you very much ibex!