ProgrammingHardProduct-company placement · C++

What is printed?

What is printed?
// C++17
struct V {
    int d[2] = {1, 2};
    int& operator[](int i)       { cout << "N"; return d[i]; }
    int  operator[](int i) const { cout << "C"; return d[i]; }
};
int main() {
    V v;
    const V& cv = v;
    v[0] = 5;
    cout << cv[0];
}
  1. A. NC5
  2. B. NN5
  3. C. CC5
  4. D. NC1

Correct answer: A. NC5

The call is resolved on the object's constness: v is non-const (N, returns a reference so the assignment writes d[0] = 5), cv is a const view of the same object (C). It reads the updated 5.

More OOP with C++ and Java questions

Exams that ask this topic