I’ve got a const method in my class, which cannot be changed to non-const. In this method, I need to call a non-const method but the compiler doesn’t let me do that.
Is there any way around it? Here is a simplified sample of my code:
int SomeClass::someMethod() const {
QColor saveColor = color();
setColor(QColor(255,255,255)); // Calling non-const method
// ....
setColor(saveColor); // restore color
return 1;
}
One of the challenges of doing
const-correctness is you can’t do it halfway. It’s either all or nothing. If you try to do it halfway, you end up in a tough spot like you are here. You end up with a niceconst-correct class being used by some crazy old, typically legacy (or written by an old curmudgeon) code that isn’tconst-correct and it just doesn’t work. You’re left wondering ifconst-correctness is worth all the trouble.You can’t — not directly. Nor should you. However, there is an alternative…
Obviously you can’t call a non-
constmethod from aconstmethod. Otherwise,constwould have no meaning when applied to member functions.A
constmember function can change member variables markedmutable, but you’ve indicated that this is not possible in your case.You could attempt to cast away
constness by doing something likeSomeClass* me = const_cast<SomeClass*>(this);but A) This will typically result in UB, or 2) It violates the whole idea ofconst-correctness.One thing you could do, if what you’re really trying to accomplish would support this, is to create a non-
constproxy object, and do nonconst-y stuff with that. To wit: