-2

I'm writing an operating system in C++. I do not have the std libs at my disposal (so I'm not sure if this works normally with std libs). It appears that if I delete an object, it only calls the destructor of the variable type (and it's parents).

For example:

Aa* aa = new Bb();
delete aa;

will only print "destructing Aa". Whereas

Bb* bb = new Bb();
delete bb;

will print both "destructing Bb" and "destructing Aa".

I tried to work around this issue by calling the sub class destructor in the super class destructor (as seen below).

Is there something I'm missing here, or will I have to resort to casting to the concrete type before the initial delete?

class Aa {
public:
    ~Aa();
};
class Bb : public Aa {
public:
    ~Bb() {
        log("destructing Bb");
    }
};

Aa::~Aa() {
    log("destructing Aa");

    // TODO checks if we are of type Bb
    // ((Bb*) this)->~Bb(); // uncomment to test calling sub class destructor
}
Chris Smith
  • 2,928
  • 4
  • 27
  • 59

2 Answers2

3

You should make the destructor of Aa virtual:

class Aa {
public:
    virtual ~Aa();
};

This is a basic concept of c++. You can read on it here (and in many other places).

Ohad Eytan
  • 8,114
  • 1
  • 22
  • 31
0

Your "Aa" destructor is not virtual, so what you are observing is the expected behaviour.

To get the behaviour you expect, declare the destructor as virtual ~Aa() = default; .

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70