ProgrammingModerateMicrosoft/Amazon SDE MCQ · GATE CS

What is printed?

What is printed?
struct S {
    void f()       { cout << "n"; }
    void f() const { cout << "c"; }
};
int main() {
    S a;
    const S b{};
    a.f();
    b.f();
    const S& r = a;
    r.f();
}
  1. A. ncn
  2. B. ncc
  3. C. nnc
  4. D. ccc

Correct answer: B. ncc

Overload resolution uses the constness of the object expression: a is non-const (n), b is const (c), and r is a reference to const, so even though it refers to a, it calls the const version (c).

More OOP with C++ and Java questions

Exams that ask this topic