ProgrammingHardInfosys · HCL
What is printed? (C++, assume <iostream> and using namespace std)
What is printed? (C++, assume <iostream> and using namespace std)
struct B { virtual void f() { cout << "B"; } };
struct D : B { void f() override { cout << "D"; } };
void show(B b) { b.f(); }
int main() { D d; show(d); }- A. D
- B. BD
- C. Compile error
- D. B
Correct answer: D. B
show takes B by value, so d is sliced into a plain B; no pointer or reference is involved, so f dispatches to B::f.
More OOP with C++ and Java questions
- What is printed? java class A { int x = 1; } class B extends A { int x = 2; } // in main: A a = new B(); System.out.print(a.x + " " + ((B)…
- What is printed? java class P { P() { init(); } void init() { } } class C extends P { int v = 5; void init() { System.out.print(v); } } //…
- What is printed? (C++, assume <iostream> and using namespace std) cpp struct M { M() { cout << "M"; } }; struct B { B() { cout << "B"; }…
- What is printed? java Integer a = 127, b = 127, c = 128, d = 128; System.out.print((a == b) + " " + (c == d));
- What does this method return? java static int f() { int x = 1; try { return x; } finally { x = 2; } }
- What is printed? (C++, assume <iostream> and using namespace std) cpp struct B { B() { f(); } virtual void f() { cout << "B"; } }; struct…