C++ | this pointer | Question 5
Predict the output of following C++ program?
#include<iostream> using namespace std; class Test { private: int x; public: Test() {x = 0;} void destroy() { delete this; } void print() { cout << "x = " << x; } }; int main() { Test obj; obj.destroy(); obj.print(); return 0; } |
chevron_right
filter_none
(A) x = 0
(B) undefined behavior
(C) compiler error
Answer: (B)
Explanation: delete operator works only for objects allocated using operator new (See this post). If the object is created using new, then we can do delete this, otherwise behavior is undefined.
See “delete this” in C++ for more examples.
Quiz of this Question
Recommended Posts:
- Double Pointer (Pointer to Pointer) in C
- C++ | this pointer | Question 4
- C++ | this pointer | Question 3
- C++ | this pointer | Question 2
- C++ | this pointer | Question 1
- C | Pointer Basics | Question 3
- C | Pointer Basics | Question 8
- C | Advanced Pointer | Question 8
- C | Pointer Basics | Question 7
- C | Pointer Basics | Question 6
- C | Pointer Basics | Question 4
- C | Pointer Basics | Question 17
- C | Pointer Basics | Question 2
- C | Pointer Basics | Question 1
- C | Advanced Pointer | Question 1



