C++ deleting this inside a member: what happens if Function() calls delete this and then the pointer is used again?\n\n#include<iostream.h>\nclass CuriousTab\n{\n int x;\n float y;\n public:\n void Function()\n {\n x = 4;\n y = 2.50;\n delete this;\n }\n void Display()\n {\n cout<< x << " " << y;\n }\n};\nint main()\n{\n CuriousTab *pCuriousTab = new CuriousTab();\n pCuriousTab->Function();\n pCuriousTab->Function();\n pCuriousTab->Display();\n return 0;\n}

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.
  • After the first deletion, the code calls Function() and Display() again on the dangling pointer.
  • No custom allocator or safety checks exist.


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.

More Questions from Objects and Classes

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion