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!
xxxxxxxxxx
}
using namespace std;
class FinancialDerivative {
public:
virtual double CalculateValue(){
return 0.0;
}
};
class Stock : public FinancialDerivative {
public:
double CalculateValue() override {
// Unique implementation for Stock
return 100.0;
}
};
class Bond : public FinancialDerivative {
public:
double CalculateValue() override {
// Unique implementation for Bond
return 200.0;
}
};
int main() {
Stock myStock;
Bond myBond;
cout << "Value of my Stock: " << myStock.CalculateValue() << endl;