ProgrammingVery hardCapgemini · Infosys

What is printed? (C++, assume <iostream> and using namespace std)

What is printed? (C++, assume <iostream> and using namespace std)
struct S {
    void f()       { cout << "n"; }
    void f() const { cout << "c"; }
};
int main() {
    S s;
    const S& r = s;
    s.f();
    r.f();
}
  1. A. nn
  2. B. cc
  3. C. nc
  4. D. cn

Correct answer: C. nc

Overloads differing in const are chosen by the object's constness: non-const s uses f(), the const reference uses f() const.

More OOP with C++ and Java questions

Exams that ask this topic