Polymorphism in C++ - Downcasting
(Page 3 of 4 )
The problem remains: how we can access, from a base pointer pointing to a derived object, the derived object's functions? One solution is downcasting. You use the dynamic_cast keyword.
The method is simple. This safe casting method will try to cast the input pointer into the specified type of pointer. If this is possible (there exists an “is a” relationship between them), it will return a correct pointer; otherwise, it will return NULL. Now we will cast out the base pointer into a derived type. Append the following lines after the earlier ones.
inTo.str(""); //clean the stream
CarContainer* carP = NULL;
carP = dynamic_cast<CarContainer*>(baseP);
if (baseP)
{
carP->appendToStream(inTo);
cout << inTo.str() << endl;
}
else
cout << "The base pointer does not points to a CarContainer Object" <<endl;
The new result allows us to do what we wanted to accomplish.
2
2
CarContainer
Car Type: Lamborghini Murcielago
Car Value : 313000
Press any key to continue . . .
This will produce a function call for the base, but this is far from polymorphism, and we would need to try to test for each existing derived class from the base. When you have a hundred derived classes, you don’t want to try this, and besides, this will lead to a switch-like logic in programming, making the code less readable and maintainable in the future when the hierarchy is expanded.
Next: The Virtual Keyword >>
More C++ Articles
More By Gabor Bernat