I copy the following text from the book More Effective C++.
Item 31: Making functions virtual with respect to more than one object.
class GameObject { ... };
class SpaceShip: public GameObject { ... };
class SpaceStation: public GameObject { ... };
class Asteroid: public GameObject { ... };
The most common approach to double-dispatching returns us to the unforgiving world of virtual function emulation via chains of if-then-elses. In this harsh world, we first discover the real type of otherObject, then we test it against all the possibilities:
void SpaceShip::collide(GameObject& otherObject)
{
const type_info& objectType = typeid(otherObject);
if (objectType == typeid(SpaceShip)) {
SpaceShip& ss = static_cast<SpaceShip&>(otherObject);
process a SpaceShip-SpaceShip collision;
}
else if (objectType == typeid(SpaceStation)) {
SpaceStation& ss =
static_cast<SpaceStation&>(otherObject);
process a SpaceShip-SpaceStation collision;
}
...
}
Here is the question:
Q1> Why we use static_cast here rather than obvious dynamic_cast?
Q2> Are they same in this case?
thank you
// updated //
In fact, I am more interested in question 2.
For example,
class base {};
class subclass : public base {};
base *pSubClass = new subclass;
subclass *pSubClass1 = static_cast<subClass*> (pSubClass);
// does the static_cast do the job correctly in this case although I know we should use dynamic_cast here?
dynamic_cast
rather thanstatic_cast
in here? – Lightness Races in Orbit