ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
struct Base {
Base() { cout << "Base-ctor "; }
~Base() { cout << "Base-dtor "; }
};
struct Derived : Base {
Derived() { cout << "Derived-ctor "; }
~Derived() { cout << "Derived-dtor "; }
};
int main() {
Derived d;
}- A. Base-ctor Derived-ctor Derived-dtor Base-dtor
- B. Derived-ctor Base-ctor Base-dtor Derived-dtor
- C. Base-ctor Derived-ctor Base-dtor Derived-dtor
- D. Derived-ctor Base-ctor Derived-dtor Base-dtor
Correct answer: A. Base-ctor Derived-ctor Derived-dtor Base-dtor
Construction always runs base-to-derived (Base-ctor then Derived-ctor), and destruction always runs in exactly the reverse order (Derived-dtor then Base-dtor), regardless of whether the destructor is virtual, since this is non-polymorphic stack destruction of the concrete type.
More OOP with C++ and Java questions
- What is printed? java public class Main { static int risky() { try { return 1; } finally { return 2; } } public static void main(String[]…
- What is printed? java class MyChecked extends Exception { MyChecked(String m) { super(m); } } public class Main { static void risky()…
- Which statement about this code is correct? java class Main { static void risky() { if (Math.random() < 2) throw new…
- What is printed? java public class Main { public static void main(String[] args) { int result = compute(); System.out.println(result); }…
- What is printed? java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); try {…
- What is printed? cpp struct Logger { Logger() { cout << "open "; } ~Logger() noexcept(false) { cout << "close "; throw…