@Faldrax:
First, if performance is an issue, a dynamic_cast is a very complex operation. I have no actual measurements, but it's probably a lot more costly than calling a virtual function. However, in most cases (as already discussed in this thread), such microscopic details have small impact on performance.
Casting in general, and specially downcasting is often a sign of bad design. In other forums, like news groups I have read, even mentioning dynamic_cast causes controversy. I've read posts saying that they would never ever even consider using such a thing. I'm not that religious though, but it's still something you should try to avoid.
In your example, I assume there is a function or class that wants to call "select_gear". In that case, why doesn't this function have a reference to a 'manual_car' in the first place? If this function operates on generic 'vehicles', it shouldn't have to deal with details on how each car is implemented.
The function probably looks something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
void Traffic::handleVehicles() {
// for each vehicle v
{
Car* c = dynamic_cast<Car*>(v);
if (c) {
AutomaticCar* ac = dynamic_cast<AutomaticCar*>(c);
if (ac) {
ac->selectAutomaticGear();
}
ManualCar* mc = dynamic_cast<ManualCar*>(c);
if (mc) {
mc->selectGear(number);
}
// do other driving stuff with car
}
Train* t = dynamic_cast<Train*>(v);
if (t) {
// ...
}
// more vehicle types...
}
}
|
Suppose you add new vehicle types, you need to update all functions that use the class hierarchy like this. Isn't is much better to say:
1 2 3 4 5 6
|
void Traffic::handleVehicles() {
// for each vehicle v
{
v->drive();
}
}
|
I could write more examples, but I hope you get my point.