Search code examples
c++inheritancecode-duplication

How to define a const class-member function that is inheriting without duplicated-code?


Im trying to define a class which (its minimal version) would look like this:

class Base{
    int i;
public:
    Base(int i_): i(i_){}
    int& at(size_t index) {return i;}
    const int& at(size_t index) const {return i;}
};

(Yes. It has an index because the class that i really want to create always need it, so lest imagine that it is necessary) And i want to inherit class like this:

class SonClass : public Base{
public:
    SonClass(int i): Base(i){}
    int& at(size_t index){
        do_something_more();
        return Base::at(index);
    }
    const int& at(size_t index) const {
        do_something_more();
        return Base::at(index);
    }
};

It seems like the versions of the at function are both the same. Is anyways to avoid this? Or any better way to do it? It seems basic, but i have like 5 functions that are all the same because of this.


Solution

  • Thi is one of the few cases where const_cast is useful. You can use it as follow:

    int& at(size_t index)
    {
        return const_cast<int&>(std::as_const(*this).at());
    }
    

    Pre c++17 you can replace std::as_const with static_cast<const my_class&>