Const and non-const version and inheritance

In my problem, I will have multiple classes that will share recipients and setters (in my case 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 to be able to do something like this:

Derived d;
d() = 1;

      

but the compiler complains that no expression is assigned. However, by doing this

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

      

works correctly. Why is this? Can't the compiler find the member function in the base class? Is there a solution to avoid overwriting a non-const method - is it a derived class?

+3


source to share


1 answer


Shouldn't the compiler look for the member function in the base class?

Yes, it is possible, but you have to be explicit. To do this, you can use a declaration using

that injects a statement into the derived class:



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

      

+4


source







All Articles