ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
struct X {
int id;
X(int i) : id(i) { std::cout << "X" << id << " "; }
~X() { std::cout << "~X" << id << " "; }
};
struct Y {
X x1{1}, x2{2}, x3{3};
};
int main(){ Y y; }- A. X1 X2 X3 ~X3 ~X2 ~X1
- B. X1 X2 X3 ~X1 ~X2 ~X3
- C. X3 X2 X1 ~X1 ~X2 ~X3
- D. X1 X2 X3 ~X2 ~X1 ~X3
Correct answer: A. X1 X2 X3 ~X3 ~X2 ~X1
Members construct in declaration order (x1, x2, x3) and are destroyed in the exact reverse order when y goes out of scope, regardless of how they are used elsewhere.
More OOP with C++ and Java questions
- What is printed? cpp struct Animal { void speak() { std::cout << "Animal"; } }; struct Dog : Animal { void speak() { std::cout << "Dog"; }…
- What is wrong with this generic class? java class Factory<T> { T create() { return new T(); } }
- What is printed? java class A { static int x = init("x", 1); static { System.out.print("sA "); } static int y = init("y", 2); static int…
- What is printed? cpp struct Base { virtual void f() { std::cout << "Base "; } }; struct Mid : Base { }; struct Derived : Mid { void f()…
- What is printed? cpp struct Base { Base(){ std::cout << "Base "; } }; struct Mem { Mem(){ std::cout << "Mem "; } }; struct Derived : Base…
- What is printed? cpp struct A { virtual void f() { std::cout << "A::f "; } }; struct B : A { void f() override { std::cout << "B::f "; }…