Question

is it ok to use const_cast in that case or are there any caveats:

class A{
public:
  A() : m_someData(5)
  {}
  int& get() { return m_someData;};

  const int& get() const {  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.

Was it helpful?

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top