Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const and non-const version and inheritance

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 ?

like image 898
tforgione Avatar asked May 23 '17 13:05

tforgione


People also ask

How is it possible to have both const and non-const version of a function?

There are legitimate uses of having two member functions with the same name with one const and the other not, such as the begin and end iterator functions, which return non-const iterators on non-const objects, and const iterators on const objects, but if it's casting from const to do something, it smells like fish.

Can a const function call a non-const function?

const member functions may be invoked for const and non-const objects. non-const member functions can only be invoked for non-const objects. If a non-const member function is invoked on a const object, it is a compiler error.

Can const function be overridden?

const is part of the signature, and leaving it off changes the signature, and thus hides the method rather than overrides it. "

What does it mean for a method to be const?

const at the end of the function means it isn't going to modify the state of the object it is called up on ( i.e., this ).


1 Answers

Shouldn't the compiler be able to look up for the member function in the base class?

Yes, it is possible, but you have to be explicit. For that you can use a using declaration, which introduces the operator to the derived class:

class Derived : public Base
{
    public:
        using Base::operator();
        int operator()() const { return value; }
};
like image 166
Rakete1111 Avatar answered Sep 29 '22 07:09

Rakete1111