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 ...

Get C++: A Dialog Programming with the C++ Standard Library now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.