Consider the following C++ code:
#include <iostream>
using namespace std;
class Hello {
public:
Hello(const char* name) : name(name)
{}
void body() {
cout << name;
cout << " body\n";
}
const char* name;
};
Hello* first;
void create() {
Hello wellington("Wellington");
first = &wellington;
}
int main() {
create();
Hello rob("Rob");
Hello james("James");
Hello donald("Donald");
// cout << "First points to: " << first << "\n";
// cout << "Rob is at: " << &rob << "\n";
// cout << "Donald is at: " << &donald << "\n";
first->body();
}
Clearly, in the function create
, we create a Hello object "Wellington", which's pointer we save in first
and which ends up being destructed after the end of this procedure. Afterwards, a few more Hello objects are created, "Donald" being the last one.
The surprising part: despite "first" pointing to a "dead" object, the body method is correctly executed.. as if first was pointing to Donald. However, the pointers are different, the Donald pointer coming after the point first
points to and Rob is located at. Another strange thing is that the name again fails to be printed correctly when the commented-out lines (printing the pointers) are included. Finally, checking the name of the pointed to object using first->name
only returned gibberish, as would be expected.
So, what's going on here? Why is the body method correctly executed with Donald's name, despite the pointed-to object no longer existing?