c++oopconst-cast

is it ok to use const_cast in member routines to avoid duplicated code


Is it okay to use const_cast in the following case, or are there any caveats:

class A {
public:
  A() : m_someData(5) {}

  int& get() { return m_someData; }

  const int& get() const { return *const_cast<A*>(this)->get(); }
private:
  int m_someData;
};

The intention is that the get routine may be much more complicated and code duplication should be avoided.


Solution

  • No. I wouldn't suggest that. I would suggest you to use const_cast in reverse direction:

    int& get() { return const_cast<int&>(const_cast<A const &>(*this).get()); };
    
    const int& get() const {  return m_someData; };
    

    That is, you should call the const member function from non-const overload, not the other way round. That way, you ensure that even the non-const version doesn't change the state of the object and the code in both functions are indeed same (because you call the const version eventually) — and there would be certainly code duplication which you want to avoid.

    If you do this the other way round, the compiler will not tell you if you modify the object in non-const version of the function and it would be incorrect to call such function from const function.