Since, you have allocated memory for your object dynamically
(using new
operator in your program), you must free it by using delete
operator. By not doing so, you are creating memory leaks
. That means, you need to keep track for memory being allocated by you and free it when you don't need them anymore. You can read about memory leaks over here.
However, for automatic
objects, the destructor
will be called implicitly when object goes out of the scope. For example,
int main()
{
foo temp;
// Do Something Interesting
return 0;
}
The output of the above program will show you the Destructor
being called.
Also, there are other problems with your program. One is you haven't declared the constructor and destructors for your class foo
under Public
lable. And second is you forgot a pair of parentheses with Destructor ~foo
. The compiler will throw error if you try to compile your program. The correct program is given below:
#include <iostream>
using namespace std;
class foo {
public:
foo() {
cout<<"This is constructor!"<<endl;
}
~foo() {
cout<<"This is destructor! "<<endl;
}
};
int main() {
foo* temp;
temp = new foo();
/*some code*/
delete temp;
return 0;
}