c++inheritancestdmapvirtual-destructor

C++: Inheriting from std::map


I want to inherit from std::map, but as far as I know std::map hasn't any virtual destructor.

Is it therefore possible to call std::map's destructor explicitly in my destructor to ensure proper object destruction?


Solution

  • The destructor does get called, even if it's not virtual, but that's not the issue.

    You get undefined behavior if you attempt to delete an object of your type through a pointer to a std::map.

    Use composition instead of inheritance, std containers are not meant to be inherited, and you shouldn't.

    I'm assuming you want to extend the functionality of std::map (say you want to find the minimum value), in which case you have two far better, and legal, options:

    1) As suggested, you can use composition instead:

    template<class K, class V>
    class MyMap
    {
        std::map<K,V> m;
        //wrapper methods
        V getMin();
    };
    

    2) Free functions:

    namespace MapFunctionality
    {
        template<class K, class V>
        V getMin(const std::map<K,V> m);
    }