Difficulty: Medium
Correct Answer: The program will report runtime error.
Explanation:
Introduction / Context:
This program demonstrates a dangerous anti-pattern: calling delete this;
inside a member function and then continuing to use the same pointer. Accessing a deleted object is undefined behavior and often leads to a crash or other runtime failure.
Given Data / Assumptions:
Function()
writes members, then immediately destroys the current object using delete this
.Function()
and Display()
again on the dangling pointer.
Concept / Approach:
Once delete this
executes, the pointer becomes dangling. Any subsequent call through it invokes undefined behavior. Typical outcomes include segmentation faults, heap corruption detection, or seemingly random output depending on memory reuse, but none of these are well-defined or reliable.
Step-by-Step Solution:
1) Allocate object with new
. 2) First Function()
: sets x
and y
, then frees *this
. 3) Second Function()
: calls a method on a freed object → undefined behavior. 4) Display()
also dereferences a dangling pointer → undefined behavior; commonly triggers a runtime error.
Verification / Alternative check:
If you remove the second and third calls (or set the pointer to nullptr
after deletion), the program would terminate safely but still exhibit questionable design.
Why Other Options Are Wrong:
Any deterministic printed output assumes defined behavior; there is none after deletion. Compile-time error does not apply because the code is syntactically valid.
Common Pitfalls:
Using delete this
without a strict ownership protocol; forgetting to set the pointer to nullptr
and guard all subsequent uses.
Final Answer:
Runtime error / undefined behavior due to use-after-free.
Discussion & Comments