Why doesn't a static cast work here?

closed account (Ey80oG1T)
Let's say that you are trying to check which object is which.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
using namespace std;

class Fish
{
public:
	virtual void 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.
static_cast<new_type>(expression)

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.

https://en.cppreference.com/w/cpp/language/static_cast
Last edited on
Topic archived. No new replies allowed.