ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
struct Animal {
virtual ~Animal() {}
virtual void speak() const { cout << "..."; }
};
struct Dog : Animal {
void speak() const override { cout << "Woof"; }
};
void announce(const Animal &a) { a.speak(); }
int main() {
Animal *animals[2];
animals[0] = new Dog();
animals[1] = new Animal();
for (int i = 0; i < 2; i++) announce(*animals[i]);
}- A. WoofWoof
- B. ......
- C. Woof...
- D. ...Woof
Correct answer: C. Woof...
Dereferencing animals[0] (a Dog*) and passing it to announce(const Animal &a) binds a reference, preserving the object's real type and vtable, so speak() dispatches to Dog::speak, printing Woof. animals[1] is a genuine plain Animal object, so it prints the base's own ..., giving Woof...
More OOP with C++ and Java questions
- What is printed? java class A { A() { System.out.print(id() + " "); } int id() { return 0; } } class B extends A { int val; B(int v) { val…
- What is printed? cpp struct Shape { virtual void draw() const { cout << "Shape "; } }; struct Group : Shape { std::vector<Shape> children…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : A { void f() override { cout << "B"; } }; struct C : B {…
- Does this compile? java public class Main { public static void main(String[] args) { try { throw new RuntimeException("x"); } catch…
- What is printed? java public class Main { public static void main(String[] args) { try { Object[] arr = new String[3]; arr[0] = 100; }…
- What is printed? cpp void f() { try { throw 10; } catch (double d) { cout << "double:" << d; } catch (int i) { cout << "int:" << i; } }…