2025-01-15 07:41 AM - last edited on 2025-01-15 08:08 AM by SofLit
I faced with an interesting issue. Here is the code:
1. Working:
void GameScreenPresenter::activate()
{
IScreen* scr = &view;
scr->Func();
}
2. Doesn't work:
void GameScreenPresenter::activate()
{
void* ptr = &view;
IScreen* scr = static_cast<IScreen*>(ptr);
scr->Func();
}
Seems like in the second option scr just nullptr. Why?
2025-01-15 08:54 AM
Hello @Wiser1201 ,
The second code fails because it uses void* and static_cast, which do not ensure type safety. If view is not of the correct type, the cast will result in undefined behavior.
The first code works because it directly assigns the address of view to an IScreen* pointer, which is valid if view is of type IScreen or derived from it.
When you assign the address of view to a void* pointer, you lose type information. This loss of type information is the root cause of the problem when you later attempt to cast the void* pointer back to an IScreen* pointer using static_cast.
Regards,