c++pointersdestructorradixderived

How to properly desructure a derived class object when derived class pointer is assigned to base class pointer?


Is it possible to delete derived class object in proper way when derived class pointer was assigned to base class pointer? Lets consider following situation:

#include <stdio.h>
#include <iostream>
#include <map>
#include <stddef.h>


class Signal{
    public:
    Signal (int val) : x(val){};
    int x;
    
    virtual ~Signal(){
        std::cout<<"base class destructor"<<std::endl;
    }

};


class Timer : public Signal{
    public:
    Timer (int val) : Signal(val), y(val+1){};
    double y;  
    virtual ~Timer(){
        std::cout<<"derived class destructor"<<std::endl;
    };
};


int main()
{
    std::cout<<"start"<<std::endl;
    Timer* t = new Timer(9);
    Signal* s = t;
    
    delete s;
    std::cout<<t->x <<std::endl;
    std::cout<<t->y <<std::endl;
    s = NULL;


if (t != NULL){
    delete t;
}
    std::cout<<"end"<<std::endl;
    return 0;
}

This will print:

start derived class destructor base class destructor -340049904 10

...Program finished with exit code 0 Press ENTER to exit console.

I just wonder if it is possible. Of course i try to avoid following asigment "Signal* s = t;" and it works.

I expected, that "end" will be printed but it is not. It seems like the program stops on "delete t". The same behavior I am observing with and without "t != NULL" check.


Solution

  • Timer* t = new Timer(9);
    Signal* s = t;
    
    delete s;
    std::cout<<t->x <<std::endl;
    

    You cannot access t, with cout << t->x after delete s;. This deletion destroyed both t and s, which are actually the same object.

    Just wait to be done with printing (or anything else) before deleting.