Question discussion

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

1749Medium 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(int x = 1) { cout << "B" << x; }
};
class D : public B {
public:
    void f(int x = 2) { cout << "D" << x; }
};
int main() {
    B* p = new D();
    p->f();
    return 0;
}
  • AD1
  • BD2
  • CB1
  • DB2
Correct answer: A

Explanation

The function is chosen at run time (D::f), but default arguments are bound statically from the pointer's type B, so the default 1 is used.

Discussion 0

Nobody has replied yet. Start the discussion!