ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
struct Animal {
void speak() { cout << "..."; }
};
struct Dog : Animal {
void speak() { cout << "Woof"; }
};
int main() {
Dog d;
Animal &ref = d;
Dog &dref = d;
ref.speak();
dref.speak();
}- A. WoofWoof
- B. ...Woof
- C. Woof...
- D. ......
Correct answer: B. ...Woof
speak() is not virtual, so each call binds statically to the reference's declared type: ref is Animal&, so ref.speak() runs Animal::speak ("..."); dref is Dog&, so dref.speak() runs Dog::speak ("Woof").
More OOP with C++ and Java questions
- 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 <<…
- What is printed? cpp struct Base { virtual void f() { cout << "Base-f "; g(); } void g() { cout << "Base-g"; } }; struct Derived : Base {…
- What is printed? java class A { static { System.out.print("A-static "); } } class B extends A { static { System.out.print("B-static "); }…