ProgrammingHardProduct-company placement · C++
What is printed?
What is printed?
struct B {
void run() { step(); }
virtual void step() { cout << "B"; }
};
struct D : B { void step() override { cout << "D"; } };
int main() {
D d;
d.run();
B b = d;
b.run();
}- A. DD
- B. DB
- C. BB
- D. BD
Correct answer: B. DB
Inside the non-virtual run(), step() is still a virtual call on *this, so for d it reaches D::step. b is a sliced copy whose dynamic type is B, so it calls B::step.
More OOP with C++ and Java questions
- What is printed? cpp class A { int x = 3; friend int peek(const A& a) { return a.x; } }; int main() { A a; cout << peek(a); }
- Which function returns a reference that is SAFE to use after the call returns?
- Why does a C++ copy assignment operator conventionally return T& (that is, this)?
- What is printed? cpp // C++17 struct V { int d[2] = {1, 2}; int& operator[](int i) { cout << "N"; return d[i]; } int operator[](int i)…
- Which lines fail to compile? cpp struct E { explicit E(int) { } }; int main() { E a(1); // L1 E b{1}; // L2 E c = 1; // L3 E d = {1}; //…
- Which line fails to compile? cpp struct P { const int id; }; int main() { P a{1}, b{2}; P c = a; // L1 a = b; // L2 }