#include <iostream>
usingnamespace std;
class Fish
{
public:
virtualvoid FishType() = 0;
};
class Carp : public Fish
{
public:
void FishType() { cout << "I am a carp\n"; }
};
class Tuna : public Fish
{
public:
void FishType() { cout << "I am a tuna\n"; }
};
void DetectFishType(Fish* fishType);
int main()
{
Tuna myDinner;
Carp myLunch;
DetectFishType(&myDinner);
DetectFishType(&myLunch);
}
void DetectFishType(Fish* fishType)
{
Tuna* tunaObj = dynamic_cast<Tuna*>(fishType);
Carp* carpObj = dynamic_cast<Carp*>(fishType);
if (tunaObj)
tunaObj->FishType();
if (carpObj)
carpObj->FishType();
}
Output:
1 2
I am a tuna
I am a carp
As you can see, I used a dynamic cast to check if an object belongs to Carp or Tuna.
But if I use a static cast instead, I get this output:
1 2 3 4
I am a tuna
I am a tuna
I am a carp
I am a carp
What is happening here? Why can't I use a static cast in this situation?
static_cast<Tuna*>(fish)
Assumes (without checking) that fish actually points to a Tuna. It's the programmer's responsibility to ensure that assumption holds. If it does not, you receive garbage (not a null pointer) that can't legally be de-referenced.
2) If new_type is a pointer or reference to some class D and the type of expression is a pointer or reference to its non-virtual base B, static_cast performs a downcast. This downcast is ill-formed if B is ambiguous, inaccessible, or virtual base (or a base of a virtual base) of D. Such static_cast makes no runtime checks to ensure that the object's runtime type is actually D, and may only be used safely if this precondition is guaranteed by other means, such as when implementing static polymorphism. Safe downcast may be done with dynamic_cast.