0

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Findus
  • 303
  • 1
  • 4
  • 17
  • 4
    It is possible (via `const_cast`) but also highly probable that you should not be doing it. – bartop Jun 10 '20 at 08:42
  • 8
    It returns that because you're not supposed to modify the object. (Read the documentation: "A const pointer to the model is returned because calls to non-const functions of the model might invalidate the model index and possibly crash your application.") This looks like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) - what are you ultimately trying to accomplish? – molbdnilo Jun 10 '20 at 08:43
  • I suspect that "`QModelIndex->model()` returns const pointer to model" should be "... returns pointer to const model". Be careful about what's `const`! – Pete Becker Jun 10 '20 at 13:24
  • 3
    Does this answer your question? [casting non const to const in c++](https://stackoverflow.com/questions/5853833/casting-non-const-to-const-in-c) – Andreas is moving to Codidact Jul 22 '20 at 11:49

1 Answers1

4

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326