In the following code:
class Object
{
public:
int a, b, c;
Object()
{
cout << "Creating an object.." << endl;
}
~Object()
{
cout << "Deleting an object.." << endl;
}
};
int main(int argc, char *[])
{
Object *obj = &(Object()); // Why is the destructor called here?
obj->a = 2; // After the destruction, why didn't this cause an access violation?
cout << obj->a; // Prints 2.
getchar();
return 0;
}
The Output is:
Creating an object..
Deleting an object..
2
In the above code,
why is the destructor called in the line Object *obj = &(Object());
? It may be because that Object()
returns a temporary object. If it is so, why didn't the next line cause an access violation as the value of obj
is the address of deleted temporary object?