ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
struct B {
    void f(int)    { cout << "Bi "; }
    void f(double) { cout << "Bd "; }
};
struct D : B {
    using B::f;
    void f(int)    { cout << "Di "; }
};
int main() {
    D d;
    d.f(1);
    d.f(2.5);
    d.f('x');
    B& b = d;
    b.f(1);
}
  1. A. Di Di Di Di
  2. B. Di Bd Bd Bi
  3. C. Di Bd Di Bi
  4. D. Bi Bd Bi Bi

Correct answer: C. Di Bd Di Bi

The using-declaration brings B's overloads of f into D's scope, but D's own f(int) hides the B::f(int) it brought in, so D sees D::f(int) and B::f(double). d.f(1) picks D::f(int); d.f(2.5) picks B::f(double); for d.f('x'), char to int is a promotion, which beats char to double, so D::f(int). The functions are not virtual, so b.f(1) through a B& calls B::f(int).

More OOP with C++ and Java questions

Exams that ask this topic