0

In this answer answer:

In particular, you are not allowed to delete a std::vector<T>* that actually points at a derived object (even if the derived class adds no members), yet the compiler generally can't warn you about it.

I understand that virtual destructor is needed if the object will be deleted through a base pointer. That's to let each class destroy it's members (at least I think so). But if the class don't have any members in itself, then why it shouldn't be deleted through the base pointer?

And also, how do I force some class to be accessed only through a pointer with it's type and not with one of the bases? will this make it normal to inherit from a class with a non-virtual destructor?

StackExchange123
  • 1,871
  • 9
  • 24
  • 3
    because the standard says so. It's undefined behavior. – bolov May 05 '20 at 00:20
  • 1
    That very answer provides a link to cppreference which states "If expression evaluates to a pointer to a base class subobject of the object that was allocated with new, the destructor of the base class must be virtual, otherwise the behavior is undefined." There is your answer. – alter_igel May 05 '20 at 00:20
  • I can't think of a way to ensure checking in your *And also*. but it gets me thinking, "Is inheritance the right solution for this questioner's problem? Perhaps I should point them at [Prefer composition over inheritance?](https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance)" – user4581301 May 05 '20 at 00:30
  • The (perhaps slightly not-what-you-had-in-mind) answer to your last question is: private inheritance. – bitmask May 05 '20 at 01:33

0 Answers0