Convert const void * pointer to a specific class pointer

I have a function declaration below

void func1(const void& * pThis) { MyClass* pMyClass = static_cast<MyClass*>(pThis); //....I use PMyClass pointer. } 

I get an error, cannot convert const void* to MyClass*

How to make this step?

+4
source share
2 answers

You can

 MyClass* pMyClass = const_cast<MyClass*>( static_cast<const MyClass*>(pThis) ); 

But this awful syntax is a hint: why then does the function have a const argument, would you like it to look like

 void func1(void * pThis) { 

Of course, you can use the shortcut with the C-style cast:

 MyClass* pMyClass = (MyClass*)pThis; 

but instead, I will correct the design if possible.

+5
source

The const problem. It cannot be discarded using static_cast . Given that you translate it to a non-constant MyClass , it makes no sense to accept the const argument anyway. You can use const_cast to remove the constant, but that would be bad - your method says it is not going to change the argument, but it actually changes it.

+4
source

All Articles