Search code examples
c++c++11constantssubscript-operator

Design : const and non-const accessors interdependance?


Possible Duplicate:
How do I remove code duplication between similar const and non-const member functions?

In the following example :

template<typename Type, unsigned int Size>
class MyClass
{
    public: inline Type& operator[](const unsigned int i) 
    {return _data[i];}

    public: inline const Type& operator[](const unsigned int i) const
    {return _data[i];}   

    protected: Type _data[Size];
};

the const and non-const operator[] are implemented independently.

In terms of design is it better to have :

  • 1) two independant implementations like here
  • 2) one of the two function calling the other one

If solution 2) is better, what would be the code of the given example ?


Solution

  • You couldn't have either implementation calling the other one without casting away constness, which is a bad idea.

    The const method can't call the non-const one.

    The non-const method shouldn't call the const one because it'd need to cast the return type.