ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
void f(int *p) { cout << "nonconst "; }
void f(const int *p) { cout << "const "; }
int main() {
    int x = 5;
    int *p = &x;
    const int *cp = &x;
    f(p);
    f(cp);
}
  1. A. nonconst nonconst
  2. B. const const
  3. C. nonconst const
  4. D. Compile-time error: call to f is ambiguous

Correct answer: C. nonconst const

p is int*, an exact match for f(int*), so it calls the non-const overload. cp is const int*, which cannot bind to f(int*) at all (would discard constness), so it exactly matches f(const int*). No ambiguity: each call has a unique exact-match overload.

More OOP with C++ and Java questions

Exams that ask this topic