ProgrammingVery hardProduct company interview · GATE level
What is printed?
What is printed?
struct P { P(const char* s) { cout << s; } };
struct B1 { B1() { cout << "1"; } };
struct B2 { B2() { cout << "2"; } };
struct X : B2, B1 {
P a, b;
X() : b("b"), a("a"), B1(), B2() { cout << "X"; }
};
int main() { X x; }- A. ba12X
- B. 21abX
- C. 12abX
- D. 12baX
Correct answer: B. 21abX
The order of a member-initialiser list is irrelevant. Bases are initialised in the order they are listed in the class head (B2, then B1), and members in the order they are declared in the class (a, then b), and only then does the constructor body run. Compilers usually warn about the misleading initialiser order, but the output is fixed: 2 1 a b X.
More OOP with C++ and Java questions
- What is printed? cpp struct A { A() { } A(const A&) { cout << "C"; } A& operator=(const A&) { cout << "="; return this; } }; void f(A a) {…
- What is printed? cpp struct B { virtual void f() = 0; }; void B::f() { cout << "B"; } struct D : B { void f() override { cout << "D"…
- What is printed? cpp struct C { static int n; C() { n++; } ~C() { n--; } }; int C::n = 0; void f(C c) { } int main() { C a; f(a); f(a); {…
- What is printed? cpp struct S { void f() { cout << "N"; } void f() const { cout << "C"; } }; void call(const S& s) { s.f(); } int main() {…
- What is printed? cpp struct B { void f(int) { cout << "Bi "; } void f(double) { cout << "Bd "; } }; struct D : B { using B::f; void f(int)…
- What happens with this code? cpp class B { public: virtual void f() { cout << "B"; } }; class D : public B { private: void f() override {…