Mark As Completed Discussion

Now that we've developed a solid understanding of polymorphism as a concept, let's dive into seeing it in action; we think doing is better than just knowing.

Let's use a real-world example relating to finance, considering you're interested in it. Imagine we're building an investment portfolio that includes multiple types of financial derivatives such as Stocks and Bonds. Each type of derivative has its unique way of calculating its Value, despite all being financial derivatives. We'll use polymorphism in this specific manner.

First, we'll create a base class FinancialDerivative with a virtual function double CalculateValue(). This function acts as an interface, promising that all classes inheriting from FinancialDerivative will implement their own version of CalculateValue().

Next, we would define our Stock and Bond classes, which inherit from FinancialDerivative and provide their versions of CalculateValue(). A Stock's value might be based on multiple factors like its price, dividends, etc., meanwhile a Bond might calculate its value based on its face value and interest rates.

This way, we can keep a collection of all our derivatives in the portfolio and call CalculateValue() on them, irrespective of whether they're a Stock or a Bond. This is polymorphism in action!

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment