Introduction to Polymorphism
To select the correct function to be called based on the actual type of an object at run time, we have to use polymorphism. Polymorphic behavior of our StockItem and DatedStockItem classes means that we can (for example) mix StockItem and DatedStockItem objects in a Vec and have the right Reorder function executed for each object in the Vec.
Susan wanted to know the motivation for using polymorphism here:
Susan: Why would you want to handle several different types of data as though they were the same type?
Steve: Because the objects of these two classes perform the same operation, although in a slightly different way, which is why they can have the same interface. In our example, a DatedStockItem acts just like a ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access