Question discussion

What is the output of the following C++ program?#include using namespace std; class B { public: virtual void f() { cout

1966Medium DSSSB TGT Computer Science 0 replies 1 views
0

What is the output of the following C++ program?

#include <iostream>
using namespace std;
class B { public: virtual void f() { cout << "B"; } };
class D : public B { public: void f() { cout << "D"; } };
void g(B b) { b.f(); }
int main() {
    D d;
    g(d);
    B& r = d;
    r.f();
    return 0;
}
  • ABB
  • BDD
  • CBD
  • DDB
Correct answer: C

Explanation

Passing d by value to g slices it into a B object, so b.f() prints B; the reference r still refers to the D object, so r.f() prints D.

Discussion 0

Nobody has replied yet. Start the discussion!