ProgrammingVery hardProduct-company placement · C++
What is printed?
What is printed?
struct B { virtual void f() { cout << "B"; } };
struct D : B { void f() override { cout << "D"; } };
int main() {
void (B::*pf)() = &B::f;
D d;
(d.*pf)();
}- A. B
- B. Compile-time error: cannot apply a B member pointer to a D
- C. D
- D. BD
Correct answer: C. D
A pointer to a VIRTUAL member function still dispatches virtually when called, so through a D object it invokes D::f even though it was formed from &B::f.
More OOP with C++ and Java questions
- What is printed? cpp template <class T> struct Base { void hi() { staticcast<T>(this)->impl(); } void impl() { cout << "B"; } }; struct X…
- What happens? cpp template <class T> T mx(T a, T b) { return a > b ? a : b; } int main() { cout << mx(3, 7); // L1 cout << mx(1, 2.5); //…
- What is printed? cpp struct A { A() { cout << "A"; } ~A() { cout << "a"; } }; struct B { B() { cout << "B"; } ~B() { cout << "b"; } }…
- Which line fails to compile? cpp string a = "a" + "b"; // L1 string b = string("a") + "b"; // L2 string c = "a" + string("b"); // L3…
- What is printed? cpp int main() { string s = "hi"; try { cout << s.at(1); s.at(5); cout << "X"; } catch (const outofrange&) { cout << "R"…
- What is printed? cpp int main() { map<string, int> m; if (m["x"] == 0) cout << m.size(); cout << m.count("y") << m.size(); }