I'm new in C ++.
And I'm trying to understand some things.
Among the use of the C++ delete operator. what I have learned is that: it deallocates the memory block pointed to by ptr (if not null), releasing the storage space previously allocated to it by a call to operator new. So I expect that if the pointer refers to the memory block of an object, it calls the destructor method of the object and deletes the object. So I wrote this code to test this:
#include <utility> // std::forward
#include <iostream> // std::cout
using std::cout;
using std::endl;
#include <string>
using std::string;
class Apartment;
class Person {
public:
Person(string n){
cout<<"init Person"<<endl;
name = n;
};
~Person(){
cout<<"Person : "<<name<<" deinit"<<endl;
};
Apartment *apartment = 0 ;
string name;
};
class Apartment {
public:
Apartment(string u){
unit = u;
cout<<"init appartamt"<<endl;
};
~Apartment(){
cout<<"Apartamt : "<<unit<<" deinit"<<endl;
};
Person *tenant = 0;
private:
string unit;
};
this is the main:
int main(){
Person *emanuele = new Person("Emanauele") ;
Apartment myAparment = Apartment("unit16C");
emanuele->apartment = &myAparment;
myAparment.tenant = emanuele;
cout<<"delete emanuele:"<<endl;
delete emanuele;
emanuele = NULL;
cout<<myAparment.tenant->name<<endl;
}
And this is the output:
init Person
init appartamt
delete emanuele:
Person : Emanauele deinit
Emanauele // WHY !!!!!
As you can see from the output, after the person object's destructor has been called, the block of memory still contains the information of the person, and it is possible to reach them through the Apartment's pointer via the command:
myAparment.tenant->name
why does this happen?