Search code examples
c++polymorphismdestructor

Why is the destructor not called when i'm declaring a pointer to an object


I have noticed that the destructor is not called when i'm declaring a pointer to an object when the program ends . Here is the code that I tried :

class B {
    public:
        B(){cout<<"cons B;";    };
        B(const B &b ){cout<<"copy B;"; };
       ~B(){cout<<"Destr B;";   };

 };

class Y:public B {
public:
    Y(){cout<<"cons Y;";    };
    Y(const Y &y ){cout<<"copy Y;"; };
    ~Y(){cout<<"Destr Y;";  };

};


int main(){
   Y *y= new Y;
   f(y);
}

The destructor is not called , the result is : cons B cons Y On the other hand if i run this code :

Y y;

The destructor is called , the result is : cons B cons Y dest Y dest B

My question is why is the destructor not being called in the first program ?


Solution

  • The destructor of an object is called when the object is destroyed, not when program exits. In your code, you never destroy the object.

    You have inadvertently created a memory leak.

    Destroy the object when you are done with it or before exiting application and its destructor would be called.

    int main(){
       Y *y= new Y;
       f(y);
       delete y;
    }