What will happen if when say delete this ?

Answer Posted / priya

Using delete this in destructor will lead to recursive loop
which will lead to Stack overflow...so avoid it over
here...however there are few times where your code with
delete this will just work fine..like in the usage of
garbage colletors in C++.Chk the below code...which works
with no issues:
class temp
{
public:
temp(){std::cout<<"Constructor"<<std::endl;}
~temp(){std::cout<<"Destructor"<<std::endl;}
void destroy() {std::cout<<"In class
temp"<<std::endl;delete this;}

};
int main()
{
temp *t = new temp;
t->destroy();
return 0;
}

Is This Answer Correct ?    2 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is pointer in c++ with example?

510


What is the use of endl?

535


How do you instruct your compiler to print the contents of the intermediate file showing the effects of the preprocessor?

577


Why do we need constructors in c++?

604


What is function overloading c++?

564






Which software is best for programming?

652


Why is c++ awesome?

565


What is difference between rand () and srand ()?

585


What are the different types of polymorphism in c++?

581


what kind of projects are suitable for c and c++

613


What does h mean in maths?

560


What is late binding c++?

536


What is the precedence when there is a global variable and a local variable in the program with the same name?

628


Define a constructor - what it is and how it might be called (2 methods)?

597


Explain pass by value and pass by reference.

586