ProgrammingModerateProduct-company placement · C++

Which line fails to compile?

Which line fails to compile?
struct P {
    int v = 1;
    int get()        { return v; }
    int cget() const { return v; }
};
int main() {
    const P p{};
    cout << p.cget();   // L1
    cout << p.get();    // L2
    cout << p.v;        // L3
}
  1. A. L1 only
  2. B. L2 and L3
  3. C. None
  4. D. L2 only

Correct answer: D. L2 only

On a const object only const member functions can be called, because this is a pointer to const. Reading a data member is fine; get() is not marked const.

More OOP with C++ and Java questions

Exams that ask this topic