ProgrammingHardAccenture · Cognizant pattern
What is printed?
What is printed?
struct N {
int v;
N(int x) : v(x) { std::cout << "N" << v << " "; }
~N() { std::cout << "~N" << v << " "; }
};
int main() {
N arr[3] = {1, 2, 3};
}- A. Compilation error: N has no default constructor
- B. N1 N2 N3 ~N1 ~N2 ~N3
- C. N1 N2 N3 ~N3 ~N2 ~N1
- D. N3 N2 N1 ~N3 ~N2 ~N1
Correct answer: C. N1 N2 N3 ~N3 ~N2 ~N1
Each int in the braced list implicitly converts to an N (the constructor isn't explicit), constructing arr[0..2] in index order: N1 N2 N3. When arr goes out of scope, array elements are destroyed in reverse index order: ~N3 ~N2 ~N1.
More OOP with C++ and Java questions
- What is printed? java class A { public String toString() { return "A"; } } class B extends A { public String toString() { return "B-" +…
- What is printed? java class Box<T> { T value; } // in main: Box<String> b1 = new Box<>(); Box<Integer> b2 = new Box<>()…
- What is printed (assume typical compiler codegen)? cpp struct Base { ~Base() { cout << "~Base "; } }; struct Derived : Base { int buf =…
- What happens when this line is compiled? java List<String>[] arr = new List<String>[10];
- What is printed? java class A { static void who() { System.out.print("A"); } } class B extends A { static void who() {…
- What is printed? java class K { int a, b; K(int a, int b) { this.a = a; this.b = b; } public int hashCode() { return 1; } public boolean…