I've been messing around with c++ and attempting to fully understand certain behaviors. Given the following program:
#include <iostream>
class Test {
public:
Test();
~Test();
void func();
};
Test::Test()
{
std::cout << "Constructor" << std::endl;
}
Test::~Test()
{
std::cout << "Destructor" << std::endl;
}
void Test::func()
{
std::cout << "Deleting this..." << std::endl;
delete this;
std::cout << "Deleted this" << std::endl;
}
int main(int argc, char **argv)
{
Test* ptr;
ptr = new Test;
ptr->func();
delete ptr;
std::cin.get();
return 0;
}
I do realize one would almost never have a reason for "delete this." However, the odd thing I noticed is when the program reaches "delete ptr," it spits out an error (as it should), but when I view the console window it shows "Destructor" on the last line.
The output I am getting is this:
Constructor
Deleting this...
Destructor
Deleted this
Destructor
I am curious as to why "Destructor" outputs twice; I would think deleting an object that doesn't exist would cause the error prior to entering the destructor. I would assume (one should probably not assume when one is a newbie) the destructor can be called as it exists in the code, and it is only when the class itself finally dies (on the closing brace of the destructor) that it gives the error when it tries to delete the specific instance. I am still curious as to why the error is not chucked (or thrown, if you prefer) as soon as delete is called on an invalid object. Given a tad further thought as I am typing, I would assume this behavior is due to 'delete' calling the destructor prior to actually destroying the class, but I am not really basing any of this on anything but my brain.
Sooo, the real question is, am I correct in what I said? I haven't really run across any websites dealing with this, and I would hate to have the wrong ideas drilled into my head.
Thanks in advance.