Modifying constant object
c++, c++11, constants, undefined-behavior
Solution
I would first ask what is meant by their ambiguous definition of "correct". You need to know the specification of the program and its intended behaviour.
As you said, if they're just asking if it compiles then the answer is 'yes'. However, if they determine correct to be safe to do, then you can discuss the facts that you state in your question.
By answering this way, the person interviewing can see how that you're analysing what you're being asked, rather than jumping straight into answering, which in my opinion is a good thing to do.
Problem
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.