I found two questions on stack overflow related to const_cast:
1) How do I remove code duplication between similar const and non-const member functions?
2) Is this undefined behavior with const_cast?
Let say we want to avoid code duplication like in answer for question 1:
struct C
{
const char& get() const
{
return c;
}
char& get()
{
return const_cast<char&>(static_cast<const C&>(*this).get());
}
char c;
};
Let's use that class like that:
C obj;
obj.get() = 'a';
As I see we cast away a constness of c
inside getter function and assign to its new value, so according to the second question, we should get undefined behavior.
Why assigning to c
is not an undefined behavior?