1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. A const member function needs to update a cache counter…

Added 30 Nov -0001

A const member function needs to update a cache counter. Which change is legitimate, and why?

  1. Cast away const, which is well defined even for an actually const object
  2. Mark the member function constexpr, since constant evaluation permits such writes
  3. Mark the member mutable, so that a const member function can still modify it Correct answer
  4. Mark the member static, because const-qualification then no longer applies to it

Correct answer

C. Mark the member mutable, so that a const member function can still modify it

15 views

MCQSEXAM

Explanation

mutable exempts a data member from the constness of the object, so a const member function can legitimately update caches, mutexes and reference counts. Casting away const and writing is undefined behaviour when the object genuinely is const, as globals and const instances are. Mutable members are still not thread-safe, so a concurrent cache needs a mutex or atomics.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is C? 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