0

Suppose I have a base class foo

class foo {
    virtual int get() const = 0;
}

and maybe 20 sub-classes foo_1, foo_2 ... inherited from foo and in the form of:

class foo_1 : public foo {
    int get() const { return 1; }
}
...
class foo_20 : public foo {
    int get() const { return 20; }
}

Suddenly life is not so easy! I have a class foo_21, which has to do this:

class foo_21 : public foo {
    int get() { member_ = false; return 0; }
    bool member_;
}

The problem is get is declared as const in the base class, and I have to change something in the sub-class foo_21. How could I find a way to go around it?

5
  • 2
    Are you sure you need inheritance and non-virtual function hiding? Commented Dec 6, 2012 at 18:43
  • Works for me: ideone.com/7kGfY1 (Note, i've edited class foo, because you've missed virtual). Commented Dec 6, 2012 at 18:43
  • To stress the point, public inheritance and virtual functions should be used only if you genuinely have a class hierarchy for which you can only determine the concrete type at runtime. Otherwise (i.e. if you have all the information at compile time), there are much better techniques (e.g. templates). Commented Dec 6, 2012 at 18:46
  • Sorry, the base is virtual... I fixed that Commented Dec 6, 2012 at 18:46
  • @hate-engine: It "works" in the sense that it compiles as long as you don't try to instantiate foo_21; but foo_21::get doesn't override foo::get. Commented Dec 6, 2012 at 18:46

1 Answer 1

7

Your base function isn't virtual, which makes all this highly speculative. Your code should already be working as you posted it (though maybe not as you expect).

You could use mutable members:

class foo_21 : public foo
{
    int get() const { member_ = false; return 0; }
    mutable bool member_;
};

It's important that the mutable variable doesn't affect the logical constness of your class. If it does, you should rework your design.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.