Is there any way to cast const class* to non-const class*?
Background is that QModelIndex->model()
returns const pointer to model. I need to access model::setData
. But I can't.
Is there any way to cast const class* to non-const class*?
Background is that QModelIndex->model()
returns const pointer to model. I need to access model::setData
. But I can't.
Is there any way to cast const class* to non const class
Yes. That is what const_cast
is for.
However, note that if you modify (non-mutable) state of a const object, then behaviour of the program is undefined. const_cast
should not be used unless you can prove that the pointed object is non-const, or that the object won't be modified through the casted result.
Even when you can prove that you aren't modifying a const object, const_cast
breaks encapsulation of the class, and may allow you to make changes that another part of the program is not expecting, which can potentially result in undefined or simply wrong behaviour. I would expect this to be true in case of calling model::setData
on QModelIndex->model()
.
const_cast
is a code smell and is better to be avoided when it isn't needed. A reasonable use case for const_cast
is to reuse implementation of a complex member function which for example has variants that return const or non-const reference to something based on the constness of *this
but doesn't modify the object. Another use case is to call an ancient API that was written before const was introduced to the C language, and consequently uses pointers to non-const on functions that never modify the pointed objects.