ProgrammingVery hardProduct-company placement · C++
What happens in C++11 or later?
What happens in C++11 or later?
struct T { ~T() { throw 1; } };
int main() {
try { T t; }
catch (int) { cout << "caught"; }
}- A. caught
- B. Nothing is printed and the program ends normally
- C. std::terminate is called; caught is not printed
- D. Compile-time error: destructors cannot throw
Correct answer: C. std::terminate is called; caught is not printed
Since C++11 destructors are implicitly noexcept unless declared otherwise, so an exception leaving ~T hits the noexcept boundary and std::terminate runs. Declaring ~T() noexcept(false) would let catch see it.
More OOP with C++ and Java questions
- What is printed? cpp struct B { virtual string who() const { return "B"; } }; struct D : B { string who() const override { return "D"; }…
- What is printed? cpp struct G { G() { cout << "G"; } ~G() { cout << "g"; } }; G g1; int main() { cout << "M"; static G s; cout << "m"; }
- Which lines fail to compile? cpp struct P { P(int) { } }; int main() { P a[3]; // L1 P b[2] = {1, 2}; // L2 vector<P> v(3); // L3…
- Which line fails to compile? cpp struct B { virtual B clone() { return new B; } virtual int id() { return 1; } }; struct D : B { D clone()…
- What is printed when compiled as C++17? cpp struct A { A() { cout << "D"; } A(const A&) { cout << "C"; } }; int main() { A a = A(A()); }
- What is printed? cpp struct B { B& operator=(int) { cout << "B"; return this; } }; struct D : B { }; int main() { D d; d = 5; }