Search code examples
c++inheritancemutable

Is it possible to derive making the parent members mutable?


Out of curiosity,

Is it possible to derive making the parent members mutable? Is there any reasonable way to modify the following code and make it compile? (Keeping foo() a const method and int a not mutable when declared in the parent class A)

class A {
protected:
    int a;
};

class B : public A {
public:
    void foo() const {
        a = 10;
    }
};

Solution

  • Normally, needing to modify a const value means you have a design error elsewhere that needs to be fixed... but if you really need to, you can do so with a const cast; e.g.

    const_cast<int&>(a) = 10;
    

    Given that you say you want to treat the base class itself as mutable, you might consider casting away the constness elsewhere, e.g. by making a member function

    A& hack() const { return const_cast<B&>(*this); }
    

    and then you can implement foo as

    hack().a = 10;
    

    This solution has the drawback of hiding the const_cast behind a function call, so you would need some way to ensure that someone reading your code knows you're doing something 'evil' (e.g. via a well chosen name for the function). This version has some advantages, however:

    • The code is, in my opinion, a bit more readable
    • It doesn't require you to repeat the type of the object you're doing this to
    • It ensures that you are only doing this to members of A, and not to members of B.