49

I add an issue on reinterpreting a variable and I don't know why..

int ProgressBar(const uint64_t data_sent, const uint64_t data_total, void const *const data)
{
    Dialog *dialog = reinterpret_cast<Dialog*> (data);
    dialog->setValue((data_sent *100) / data_total);
}

the reinterpret_cast seems not allowed and say

reinterpret_cast from 'const void *) to Dialog * casts away qualifiers

Any idea

3
  • 6
    reinterpret_cast can't cast away cv-qualifiers Commented Jan 17, 2015 at 2:53
  • @Nick: The last const you put in there has no effect.
    – Ben Voigt
    Commented Jan 17, 2015 at 2:58
  • 3
    Um, why are you trying to get rid of the const here? That sounds unsafe. Commented Jan 17, 2015 at 3:07

2 Answers 2

67

As Nick Strupat stated in comment,

reinterpret_cast can't cast away cv-qualifiers

So you can use reinterpret_cast and const_cast together.

Dialog *dialog = const_cast<Dialog*>(reinterpret_cast<const Dialog *>(data));
0
11

You need to also use a const_cast to remove const qualifiers. Also, casting from void * can use static_cast, it does not need to reinterpret. For example:

Dialog const *dialog = static_cast<Dialog const *>(data);
Dialog *d2 = const_cast<Dialog *>(dialog);

However , make sure that the Dialog is actually not a const object; attempting to modify a const object (presumably setValue does this) causes undefined behaviour.

I'd suggest rethinking the interface to ProgressBar to avoid needing this cast.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.