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);
}- A. Di Di Di Di
- B. Di Bd Bd Bi
- C. Di Bd Di Bi
- 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
- What happens with this code? cpp class B { public: virtual void f() { cout << "B"; } }; class D : public B { private: void f() override {…
- What is printed? cpp struct B { virtual const char who() const { return "B"; } }; struct D : B { const char who() const override { return…
- What is printed? cpp struct A { int v = 0; A() { cout << "A"; } }; struct B : A { B() { cout << "B"; } }; struct C : A { C() { cout <<…
- What is printed? cpp void f(bool) { cout << "bool "; } void f(std::string) { cout << "string "; } void g(int) { cout << "int "; } void…
- What is printed on a typical platform (16-bit short, 32-bit int)? cpp int i = -1; unsigned int u = 1; short s = -1; unsigned short us = 1…
- Which lines fail to compile? cpp struct A { explicit A(int) { } }; struct B { B(int) { } }; void takeA(A) { } void takeB(B) { } int main()…