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 questionsThe 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.
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.
- 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.
Keep practicing
Take the free CPA-21-02 practice test
Ten exam-style questions with answers and explanations, plus the exam facts and study guides.
More questions
Other CPA-21-02 practice questions
- Question 1What happens when you attempt to compile and run the following code? #include using names…
- Question 2What happens when you attempt to compile and run the following code? #include #include us…
- Question 3Which of the following statements are correct about an array? int tab[10];
- Question 4What happens when you attempt to compile and run the following code? #include #include us…
- Question 5What is the output of the program if characters 'h', 'e', 'l', 'l' , 'o' and enter are su…
- Question 6What happens when you attempt to compile and run the following code? #include using names…
