0

Case-1:

Base class has a dynamically allocated variable but the derived class doesn't and then I do:

Base* p = new Derived;
delete p;

Case-2:

Both base and derived class have dynamically allocated variables (derived has additional dynamically allocated variables besides those inherited). Again, I do:

Base* p = new Derived;
delete p;

Case-3: Base class has no dynamically allocated variables but the derived one does. I do this again:

Base* p = new Derived;
delete p;

Case-4: Neither base nor derived class has any dynamically allocated variable. Again I do:

Base* p = new Derived;
delete p;

Or does it cause undefined behaviour in all cases if the virtual keyword is ignored?

Tim Southee
  • 51
  • 2
  • 6

1 Answers1

4

All of them.

If you delete using a pointer that is not the same type as the actual object, the compiler doesn't know how to do it properly unless the destructor is virtual. At that point you get undefined behavior, even if it appears to work properly.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • In the general case all four cases are problematic, but iff the dynamic allocation is the only concern, only case 2 and 3 are problematic, right? – Waldheinz Apr 03 '15 at 17:01
  • @Waldheinz: Undefined behaviour is always a concern, so dynamic allocation can't be the only concern. – Mike Seymour Apr 03 '15 at 17:03
  • @MikeSeymour I'm not that deep into C++ to know if that behaviour is undefined because C++ says so or if there can be cases where it's actually safe to do. But it is always undefined, here's some detail: http://stackoverflow.com/questions/6171814/why-is-it-undefined-behavior-to-delete-an-array-of-derived-objects-via-a-base – Waldheinz Apr 03 '15 at 17:06
  • @Waldheinz it's always dangerous to rely on the internal workings of the compiler, because those are subject to change. Even though it appears the dynamic allocation should be the only difference, you can't guarantee it. – Mark Ransom Apr 03 '15 at 17:28