How to call a non-const method from a const method?

laurent picture laurent · Nov 30, 2011 · Viewed 21.9k times · Source

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;
}

Answer

sharptooth picture sharptooth · Nov 30, 2011

You could use const_cast on this pointer,

int SomeClass::someMethod() const {
    const_cast<SomeClass*>( this )->setColor(...);// Calling non-const method
    //whatever
}

but if you do that for an object that was originally declared const you run into undefined behavior.

So this:

SomeClass object;
object.someMethod();

is okay, but this:

const SomeClass object;
object.someMethod();

yields undefined behavior.

The real solution is that your const function should not be const in the first place.