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);
}- A. nonconst nonconst
- B. const const
- C. nonconst const
- 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
- Does this compile? java class Outer { private int x = 5; class Inner { void show() { System.out.println(x); } } }
- What is printed? cpp struct Base { virtual void f() { cout << "Base"; } }; struct Derived : Base { void f() { cout << "Derived"; } }; int…
- What is printed? java class Picker { static void f(int a, int b) { System.out.print("fixed"); } static void f(int... a) {…
- What happens when this is compiled? cpp struct Base final { virtual void f() { cout << "Base"; } }; struct Derived : Base { };
- What is printed? cpp struct Base {}; struct Derived : Base {}; void f(Base b) { cout << "Base"; } void f(Derived d) { cout << "Derived"; }…
- What is printed? cpp struct Shape { virtual double area() const = 0; virtual ~Shape() = default; }; struct Square : Shape { double s…