If you are new to the world of object-oriented programming, then your first thought after reading the title of this article is "what the heck could ever transform in code?" The answer is not so trivial that I can explain it in just a sentence, but join me throughout this article and you will get the idea.
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);
cout << inTo.str() << endl;
cout << "The base pointer does not points to a CarContainer Object" <<endl;
The new result allows us to do what we wanted to accomplish.
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.