Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are STL containers designed to allow inheritance? [duplicate]

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?

like image 625
mip Avatar asked Dec 30 '12 07:12

mip


Video Answer


1 Answers

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.

like image 151
Alok Save Avatar answered Oct 11 '22 22:10

Alok Save