-1

So I has these Base class and sub class.

#include <iostream>

class BaseDevice
{
public:
    int _pin;
    BaseDevice() { std::cout << "base constructor\n"; }
    virtual void read() = 0;
    virtual ~BaseDevice() { printf("destroyed base\n"); }
    void debugThis() { printf("debug %i \n", _pin); }
};


class Morse : public BaseDevice
{
public:
    Morse(int pin) : BaseDevice() { _pin = pin; }
    ~Morse() { printf("destroyed morse\n");}

    void read() { std::cout << "read"; }

private:

};

int main()
{

    BaseDevice *morse[5];

    morse[0]  = new Morse(13);
    morse[0]->debugThis();
    morse[1] = new Morse(6);
    morse[1]->debugThis();
    delete morse[1];
    morse[1]->debugThis();

    return 0
}

So when I delete morse[1], it says it destroyed 'morse' & 'baseDevice'… But when I called morse[1]->debugThis() right after the delete, it's still printed out the _pin = 6. So the object pointer is still there. It's not deleted/destroyed?

Mistergreen
  • 1,052
  • 1
  • 8
  • 16

2 Answers2

4

It is destroyed, you're running into undefined behavior - anything can happen.

After you call delete, it's no longer legal to access the pointer.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

Generally deleting or freeing memory does not mean that system will put zero or some garbage value there. It mean that system will reuse that memory in further allocation. So after deleting the content is still there. So occurs the same output.

Shashwat Kumar
  • 5,159
  • 2
  • 30
  • 66