ProgrammingHardAccenture · Cognizant pattern
What is printed?
What is printed?
struct Base {
void who() { cout << "Base"; }
};
struct Derived : Base {
void who() { cout << "Derived"; }
};
int main() {
Base *p = new Derived;
p->who();
}- A. Derived
- B. Base
- C. Compilation error: who() redefined
- D. BaseDerived
Correct answer: B. Base
who() is not declared virtual, so the call is resolved statically using the pointer's compile-time type Base*, calling Base::who() regardless of the actual object being a Derived.
More OOP with C++ and Java questions
- What is printed? cpp struct Base { static int count; Base() { count++; } }; int Base::count = 0; struct Derived : Base {}; int main() {…
- What is printed? cpp struct Animal { void speak() { cout << "..."; } }; struct Dog : Animal { void speak() { cout << "Woof"; } }; int…
- What is printed? (function-local static) cpp int next() { static int n = 0; return ++n; } int main() { cout << next() << next() << next()…
- What is printed? java class A { void greet() { System.out.print("A-inst "); } static void greet(int x) { System.out.print("A-static "); }…
- What is printed? cpp class Base { public: void info() { cout << "Base::info "; helper(); } void helper() { cout << "Base::helper"; } }…
- What is printed? cpp struct A { int v = 1; virtual void show() { cout << v; } }; struct B : A { int v = 2; void show() override { cout <<…