0

I have recently seen some strange approach on overload a non-const method with a const one.

Lets say we have

const int& foo() const {
  return 42;
}

And now the const version was implemented like this

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

Is there a reason behind this? And if this is the right way, when should i use this approach?

Symlink
  • 302
  • 2
  • 9
  • It avoids duplication of code - imagine if the first one had 100 lines instead of 1 – M.M Feb 23 '22 at 00:37

0 Answers0