1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. An object is defined as const int c = 10; and const_cast…

Added 30 Nov -0001

An object is defined as const int c = 10; and const_cast is used to write through a pointer to it. What is the result?

  1. A compile error is guaranteed on every conforming compiler, because const_cast is rejected there
  2. Undefined behaviour, because modifying an object that is genuinely const is not allowed Correct answer
  3. It works and c becomes the new value, because the pointer overrides the const qualifier
  4. It is well defined, but the write is silently discarded, so c keeps its original value of 10

Correct answer

B. Undefined behaviour, because modifying an object that is genuinely const is not allowed

15 views

MCQSEXAM

Explanation

const_cast may remove const from a reference or pointer, but writing through it is undefined behaviour when the referenced object was originally defined const, because the compiler may place it in read-only memory or fold the value into computations. The cast is legitimate only when the underlying object is non-const, for example an interface taking const that must call a legacy non-const function.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is B? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C++ and Object-Oriented Programming MCQs

Practise all C++ and Object-Oriented Programming MCQs

Similar MCQs