Possible Duplicate:
Is it okay to inherit implementation from STL containers, rather than delegate?
My question is related to Why don't STL containers have virtual destructors? Some people (including author of the former question) are convinced that not having virtual dtor implies that class is not inheritable. I am skeptical about such a strong statement, so I asked for the source or some reasoning but most respondents remain silent. Also nobody responded to my answer
So I think it is good idea to question the assumptions made in the former question and clarify this important issue. Are STL containers designed to allow inheritance or not? And more generally: is virtual destructor required for inheritance?
Are STL containers designed to allow inheritance or not?
Standard library containers allow Inheritance. Nothing stops you from inheriting from a standard library container class. You will not get any compilation errors if you do so.
But what they are not designed for is to allow is destruction of your derived class object through Base class pointer. So if you want to use inheritance for such a scenario(in short for dynamic polymorphism) then standard library containers are clearly not designed for it.
Is virtual destructor required for inheritance?
Base class destructor is only required to be virtual if you intend to call delete
on base class pointer pointed to a derived class object. It will result in Undefined behavior if base class destructor is not virtual.
So to summarize, the rule is:
If you need inheritance for dynamic polymorphism standard library container classes are not designed for it, but If you don't need that you can safely inherit from them.
Note: Your analysis in the answer link you provided is correct. It just didn't get responses probably because the answer was posted long(a few years) after the original Q was posted. You have my +1 there now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With