Search code examples
c++castingstatic-cast

static_cast throws error but C-style cast works


When I use static_cast:

const C* cObj; // C is a user-defined class
void* obj = static_cast<void*>(cObj);

I get the error:

Conversion loses qualifiers

But when I use C-style cast, it works:

const C* cObj;
void* obj = (void*)cObj;

Why is it so?

What is the correct way to do it via C++ style casts?


Solution

  • Why is it so?

    C-style cast works because has the power of multiple C++ casts combined. For example, it can cast away const-ness and reinterpret the pointer type at the same time. The process used by C++ compilers to decide how to interpret a particular C cast is described here.

    A C++ way to cast a constant pointer is to cast it to another constant pointer, like this:

    const void* obj = static_cast<const void*>(cObj);
    

    If you also need to cast away const-ness, you can chain casts like this:

    void* obj = const_cast<void*>(static_cast<const void*>(cObj));
    

    Regular precautions of const_cast apply as usual: if the pointer that you are casting is pointing to a constant object, modifying that object through a non-const pointer after the cast causes undefined behavior.