Skip to main content
Associate II
January 15, 2025
Solved

void pointers

  • January 15, 2025
  • 1 reply
  • 549 views

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?

Best answer by GaetanGodart

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,

1 reply

GaetanGodart
GaetanGodartBest answer
Moderator
January 15, 2025

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,

Gaetan GodartSoftware engineer at ST (TouchGFX)