Const and non-const version and inheritance

Viewed 914

In my problem, I will have a few classes that will share getters and setters (in my case, the operator()). Suppose I have the following

class Base
{
    public:
        int& operator()() { return value; }
        int operator()() const { return value; }
    protected:
        int value;
};

class Derived : public Base
{
    public:
        int operator()() const { return value; }
};

I expected being able to do something like this :

Derived d;
d() = 1;

but the compiler complains saying that the expression is not assignable. However, doing this

Derived d;
d.Base::operator()() = 1;

works correctly. Why is that ? Shouldn't the compiler be able to look up for the member function in the base class ? Is there a solution to avoid rewriting the non-const method is the derived class ?

1 Answers
Related