ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
struct S {
    void f()       { cout << "N"; }
    void f() const { cout << "C"; }
};
void call(const S& s) { s.f(); }
int main() {
    S a;
    const S b{};
    S* p = &a;
    const S* q = &a;
    a.f(); b.f(); p->f(); q->f(); call(a);
}
  1. A. NCNNN
  2. B. NCNCC
  3. C. NCNCN
  4. D. NNNNN

Correct answer: B. NCNCC

Overloads on const are chosen by the static type of the object expression, not by whether the object itself was declared const. a and *p are non-const, so N. b is const, and *q and the parameter s are accessed through pointer- or reference-to-const, so the const overload runs even though q and s refer to the non-const a.

More OOP with C++ and Java questions

Exams that ask this topic