ProgrammingHardProduct-company placement · C++
What is printed?
What is printed?
struct P {
int a, b;
P() : P(1) { cout << "x"; }
P(int a) : P(a, 2) { cout << "y"; }
P(int a, int b) : a(a), b(b) { cout << "z"; }
};
int main() { P p; cout << p.a << p.b; }- A. zyx12
- B. xyz12
- C. xyz00
- D. zyx10
Correct answer: A. zyx12
With delegating constructors (C++11) the target constructor runs completely first, then the delegating constructor's body: P(int, int) prints z, then P(int) prints y, then P() prints x.
More OOP with C++ and Java questions
- Which lines fail to compile? cpp struct F { explicit operator bool() const { return true; } }; int main() { F f; if (f) cout << "Y"; // L1…
- What is printed? cpp struct M { operator int() const { return 7; } }; int main() { M m; cout << m + 1; }
- What is printed? cpp // C++17 struct Counter { int n = 0; int operator()() { return ++n; } }; int main() { Counter c; c(); c(); Counter d…
- Which line fails to compile? cpp class B { public: void f() { cout << "f"; } void g() { cout << "g"; } }; class D : private B { public…
- What is printed? cpp struct A { void hi() { cout << "A"; } }; struct B { void hi(int) { cout << "B"; } }; struct C : A, B { }; int main()…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B { virtual void f() { cout << "B"; } }; struct C : A, B {…