Challenge: Enumerating the array


#1

I’ve solved the challenge, thanks to helpful posts to this forum. But I don’t understand why this enumeration works

for (StockHolding *stock in stocks) {
            NSLog(@"Bought at %.2f, now at %.2f. Number of shares %d. Wins %.2f", 
                  [stock purchaseSharePrice],
                  [stock currentSharePrice],
                  [stock numberOfShares],
                  [stock valueInDollars] - [stock costInDollars]);
        }

The for statement says the the enumeration will run through a list of StockHolding objects. But some of them are ForeignStockHolding objects. How does it know how to handle them properly?

If i change the first line to

everything still works, but I don’t understand why. I would expect all stock - including domestic - to be hit with the overridden methods for valueInDollars and costInDollars from the ForeignStockHolding implementation.

Can somebody help me get my head around it?

Lars


#2

Hopefully this helps.

In the abstract, just looking at your code snippet, no, I couldn’t tell you which element of your array is going to respond with the overridden methods, and neither can the compiler

Thankfully, all of this is decided at runtime.

So, as your loop runs, each individual object is asked to respond to the message, and for each object, the method invoked will be the overridden version if that holding happens to be foreign.

So by changing StockHolding to ForeignStockHolding at compile time, you aren’t changing the runtime behavior at all, because each object still is either foreign or not, and the runtime can sort it out.


#3

[quote=“macintux”]Hopefully this helps.
So by changing StockHolding to ForeignStockHolding at compile time, you aren’t changing the runtime behavior at all, because each object still is either foreign or not, and the runtime can sort it out.[/quote]

Thank you, that clarified things a lot. Guess I need to do a lot more of these exercises before it sticks.