[ Post New Message | Post Reply to this One | Send Private Email to Steve Heller | Help ]

Virtual functions are tricky

from Steve Heller (stheller@koyote.com)
UndatedStockItem::Reorder is called by the statement "m_Worker->Reorder(os);" in the StockItem::Reorder function, because the object pointed to by "m_Worker" is an UndatedStockItem object.

That's why Reorder is a virtual function: so that the correct version of Reorder will be called depending on the actual type of the object pointed to, rather than depending on the type of the pointer itself.

You see, the type of the object pointed to can depend on how it was created, as it does in the case of dated vs. undated objects. That's the whole point of virtual functions: to allow the correct version of a function to be called without having to have an "if" statement selecting it. This allows extensions to be added to the types handled without having to modify existing code.

By the way, you shouldn't feel bad if you have trouble understanding the purpose of virtual functions; that's probably the hardest lesson to learn when getting started with object-oriented programming.

(posted 7038 days ago)

[ Previous | Next ]