ProgrammingModerateMicrosoft/Google SDE MCQ · GATE CS
What is printed?
What is printed?
struct B { }; struct D : B { };
void f(B&) { cout << "B"; }
void f(D&) { cout << "D"; }
int main() {
D d;
B& b = d;
f(b);
f(d);
}- A. DD
- B. BB
- C. BD
- D. DB
Correct answer: C. BD
Overload resolution uses the static type of each argument: b is a B&, so f(B&) is chosen even though it refers to a D. Only virtual member functions dispatch on the dynamic type.
More OOP with C++ and Java questions
- What is printed? cpp struct T { int id; T(int i) : id(i) { cout << "+" << id; } ~T() { cout << "-" << id; } }; T g(1); void f() { static T…
- What is printed? cpp int main() { int a = 1, b = 2; int& r = a; r = b; r = 5; cout << a << b; }
- What is printed? cpp void g(int&) { cout << "L"; } void g(int&&) { cout << "R"; } template <class T> void fwd(T&& x) { g(x)…
- Which line fails to compile? cpp struct B { void hi() { } }; class D1 : B { }; // note: class struct D2 : B { }; // note: struct int…
- Which line fails to compile? cpp struct M { int v; M(int x) : v(x) { } M operator+(const M& o) const { return M(v + o.v); } }; int main()…
- What is printed? cpp int main() { vector<int> a(3, 5); vector<int> b{3, 5}; vector<int> c; c.reserve(10); cout << a.size() << b.size() <<…