Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting the proper way in C++

Tags:

c++

casting

I apologise if this isn't considered a good enough question (since my own solution just works, so I don't actually have a problem), but here goes.
I mean, I was brought up on C and I only learned C++ later, so maybe I'm biased, but still.

In this particular case, there is one library that returns a const char*, while another library needs a void* as input. So if I want to call the second library with the result of the first, I will need to write

second(const_cast<void*>(static_cast<const void*>(first())));

Right? That's the only proper way, right?

like image 950
Mr Lister Avatar asked Feb 21 '23 23:02

Mr Lister


1 Answers

A char* can be implicitly converted to a void*, so your code can be simplified to this:

second(const_cast<char*>(first()));

This is only safe if the definition of second operates as if its parameter had the type const void*.

like image 112
GManNickG Avatar answered Mar 08 '23 12:03

GManNickG