static_cast throws error but C-style cast works

1k views Asked by At

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?

2

There are 2 answers

0
Sergey Kalinichenko On BEST ANSWER

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.

0
Richard Hodges On

If the path to ruin is really your intent...

struct C;

template<class T>
T* daringly_remove_const_and_damn_the_consequences(T const* p)
{
    return const_cast<T*>(p);
}

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