Question discussion

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

932Medium 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();
    B *p = &d; p->f();
}
  • ABDD
  • BDDD
  • CBBB
  • DBBD
Correct answer: A

Explanation

g() takes B by value, so d is sliced to a B and prints B; the reference and the pointer keep the dynamic type D, so each prints D.

Discussion 0

Nobody has replied yet. Start the discussion!