ProgrammingHardProduct-company placement · C++

What happens when this is compiled?

What happens when this is compiled?
struct A {
    int v = 0;
    int& get() const { return v; }
};
  1. A. It compiles; get() returns a modifiable reference
  2. B. Compile-time error: cannot bind int& to the const member v
  3. C. It compiles but writing through the reference is undefined behaviour
  4. D. Compile-time error: const functions cannot return references

Correct answer: B. Compile-time error: cannot bind int& to the const member v

Inside a const member function this points to a const A, so v is a const int and cannot initialise a non-const int&. Returning const int& (or by value) fixes it.

More OOP with C++ and Java questions

Exams that ask this topic