Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 691
vlad_tepesch Avatar asked Feb 13 '23 11:02

vlad_tepesch


1 Answers

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.

like image 95
Nawaz Avatar answered Feb 16 '23 01:02

Nawaz