ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
struct Animal {
void speak() { std::cout << "Animal"; }
};
struct Dog : Animal {
void speak() { std::cout << "Dog"; }
};
int main() {
Animal *a = new Dog();
a->speak();
}- A. AnimalDog
- B. Dog
- C. Animal
- D. Compilation error
Correct answer: C. Animal
speak() is not declared virtual, so the call is resolved statically using the pointer's declared type (Animal*), not the object's dynamic type. No vtable is involved, so Animal::speak runs.
More OOP with C++ and Java questions
- What is wrong with this generic class? java class Factory<T> { T create() { return new T(); } }
- What is printed? java class A { static int x = init("x", 1); static { System.out.print("sA "); } static int y = init("y", 2); static int…
- What is printed? cpp struct Base { virtual void f() { std::cout << "Base "; } }; struct Mid : Base { }; struct Derived : Mid { void f()…
- What is printed? cpp struct Base { Base(){ std::cout << "Base "; } }; struct Mem { Mem(){ std::cout << "Mem "; } }; struct Derived : Base…
- What is printed? cpp struct A { virtual void f() { std::cout << "A::f "; } }; struct B : A { void f() override { std::cout << "B::f "; }…
- Which statement about this program's behaviour is true? cpp struct S { int b; int a; S() : a(1), b(a + 1) { } }; int main() { S s…