CPA-21-02 practice question 22 of 35

What happens when you attempt to compile and run the following code? #include #include using namespace std; class First { string *s; public: First() { s = new string("Text");} ~First() { delete s;} void Print(){ cout

Full set: 257 questions
Answer options
A: It prints: Text
B: Compilation error
C: Runtime error. Correct answer
D: None of these
Correct Answer:
C. Runtime error.
Explanation

The code explicitly calls the destructor FirstObject.~First();, which executes delete s; and deallocates the memory holding the string. However, FirstObject is a local object with automatic storage duration. When main() terminates, the object goes out of scope, and the destructor is implicitly called a second time by the runtime environment. This results in a double deletion of the same memory address (since s was not set to nullptr after the first deletion), which causes undefined behavior. This typically manifests as a runtime error or program crash.

Why Incorrect

A: While it may briefly print "Text", the program subsequently crashes due to undefined behavior, making "Runtime error" the most accurate description of the program's execution state. B: The code is syntactically valid and will compile successfully; explicit destructor calls are permitted in C++. D: Option C correctly identifies the runtime error caused by the double free.

References

- ISO/IEC 14882:2017 (C++17 Standard), Section 6.7.3 [basic.life], Paragraph 8.

- Stroustrup, B. (2013). The C++ Programming Language (4th Ed.). Addison-Wesley. Chapter 11.2.

Scroll to Top