I was looking through the interview questions to a junior C++ developer position. The question is (quote):
Is the following code correct?
struct Foo
{
int i;
void foo ( void ) const
{
Foo* pointer = const_cast<Foo*>(this);
pointer->i = 0;
}
};
I would answer:
The code itself is valid according to the C++03 and c++11 standards and will compile successfully. But it may invoke an undefined behavior during assignment pointer->i = 0; if the instance of the class on which foo() is being called is declared as const.
I mean that following code will compile successfully and result in undefined behaviour.
struct Foo
{
int i;
Foo ( void )
{
}
void foo ( void ) const
{
Foo* pointer = const_cast<Foo*>(this);
pointer->i = 0;
}
};
int main ( void )
{
Foo foo1;
foo1.foo(); // Ok
const Foo foo2;
foo2.foo(); // UB
return 0;
}
Is my answer correct or I am missing something? Thank you.