ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
struct Base { virtual void show() { cout << "Base "; } };
struct Derived : Base { void show() override { cout << "Derived "; } };
void byRef(Base& b) { b.show(); }
void byVal(Base b) { b.show(); }
int main() {
Derived d;
byRef(d);
byVal(d);
}- A. Derived Base
- B. Base Derived
- C. Derived Derived
- D. Base Base
Correct answer: A. Derived Base
A reference parameter binds to the actual Derived object, so byRef preserves polymorphism and calls Derived::show. A by-value parameter copies only the Base part (slicing), so byVal always calls Base::show no matter what was passed.
More OOP with C++ and Java questions
- What is printed? java // in main: List<String> ls = new ArrayList<>(); List<Integer> li = new ArrayList<>()…
- Which statement about this class is correct? java class Example<T> { void method(List<String> list) { System.out.println("string-list"); }…
- What is printed? java class Util { static <T> T firstNonNull(T a, T b) { return a != null ? a : b; } } // in main: String s =…
- What is printed? java class Container<T extends Comparable<T>> { T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; } } // in main…
- What is printed? java class Node<T> { T data; static int count; { count++; } Node(T d) { data = d; } } // in main: new Node<Integer>(1)…
- What is printed? java class Base { protected void show() { System.out.println("Base.show"); } } class Derived extends Base { @Override…