Reputation: 876
SO i have two classes Tuna
and Carp
which have the member methods becomeDinner
and Talk
respectively:
Now I have this code:
Tuna* myDum = new Tuna();
auto myCastedDum = reinterpret_cast<Carp*>(myDummy);
myCastedDum->Talk();
In my book it says:
Again, definitely not.
reinterpret_cast
changed only the interpretation of the pointer, and did not change the object being pointed to (that is still aTuna
). Calling aTalk()
function on aTuna
object will not give the results you are looking for, and could possibly cause an application error.
Now this seams to not be the case, when I try to call the talk
method on myCastedDum
it works as if it was a Carp
object and when I try to call becomeDinner()
it tells me that it isn't a member, I don't understand, we cast it to Carp explicitely with reinterpret_cast
so why would that be unexpected if we explicitely tell the compiler to do it?
What does changing the interpretation of the pointer mean?
Thanks in advance.
Upvotes: 0
Views: 81
Reputation: 87944
The cause of your misunderstanding seems to be that in this code
Tuna* myDummy = new Tuna();
auto myCastedDum = reinterpret_cast<Carp*>(myDummy);
myCastedDum->Talk();
you think that reinterpret_cast
is changing your Tuna
object into a Carp
object. That's not true. All it is doing is converting a Tuna pointer into a Carp pointer. But that Carp pointer is still pointing at a Tuna object, in other words the underlying object has not changed.
So when you use the Carp pointer to call a Carp method you get undefined behaviour, because there is no Carp object for the Carp method to work on.
The reason you are able to call Carp::Talk()
is that all the compiler is checking is the type of the pointer. You do have a Carp pointer, even if it not pointing at a Carp object, so the compiler will let you call Carp::Talk. Using reinterpret_cast
is a way of overriding the normal safety checks that the language has. That's why it should be used with care.
Upvotes: 1