Mr Lister
Mr Lister

Reputation: 46619

Casting the proper way in C++

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?

Upvotes: 4

Views: 294

Answers (1)

GManNickG
GManNickG

Reputation: 504303

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*.

Upvotes: 8

Related Questions