Skip to content
Related Articles
Open in App
Not now

Related Articles

C++ | this pointer | Question 5

Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 10 Jul, 2018
Improve Article
Save Article
Like Article

Predict the output of following C++ program?

using namespace std;
class Test
  int x;
  Test() {x = 0;}
  void destroy()  { delete this; }
  void print() { cout << "x = " << x; }
int main()
  Test obj;
  return 0;

(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

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!