Practice mode C++

What is the result of using const_cast to remove const and then modifying an object that was originally defined as const?

Correct answer B. Undefined behaviour

Explanation

const_cast can legally strip const from a pointer or reference, and writing through it is fine if the object itself was originally non-const. But if the object was defined const, such as const int x = 5;, modifying it is undefined behaviour; it may live in read-only memory or be folded into constants by the compiler. const_cast is mainly for calling legacy APIs.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.