Re: CMAP under vs2005+
Giovanni Dicanio wrote:
Suppose CMapEx inherits from std::map, and you write code like this:
std::map<...> * pMyMap = new CMapEx< ... >();
You could write code like this, because CMapEx *is-a* std::map.
Then, after using pMyMap, you delete it:
BOOM! The problem is that std::map has no *virtual* destructor, so the
above statement causes a subtle bug, because the CMapEx destructor is
Instead, if std::map had had a virtual destructor, the derived class
destructor (~CMapEx) would have been called.
This is a reason why inheritance is not very good in that particular
Ok. I see. Small note: I am not a CS major, but I was confused with how
you illustrated polymorphism as a dynamic instantiation.
Nonetheless, I see the point. This does work when you declare it as a
typedef. Like in the example you have:
typedef MyMap< string, string > CMyMapString;
cout << "*** Polymorphic test:" << endl;
CMyMapString *pSomeMap = new CMyMapString;
assert( pSomeMap->size() == 0 );
This will call the destructor.
I was thinking more along the lines of polymorphism like so;
class MyMap2 : public CMapEx<CString>
cout << "MyMap2 constructor." << endl;
cout << "MyMap2 destructor." << endl;
This works as expected.
Besides needing to make a typedef for the class std container template,
is there something else I am missing here?
Polymorphism has nothing to do with typedef's. typedef's are just a notational
convenience; they do not change an incorrect program into a correct one.
Your TestPolymorphism function does not test polymorphism, because it uses only
a single class.
Look at Giovanni's example again. He creates a CMapEx<> object on the heap, but
assigns it to a base class std::map<> pointer. If this base class pointer is now
deleted, there is a problem, because the CMapEx<> destructor is not called. Such
a program actually has undefined behavior (though in practice I'm sure that most
compilers will simply call the base class destructor, which would be OK if the
derived class destructor does not do anything.).
I'm sure you will say: "But I would never use my CMapEx<> class in that way".
I'm sure you would not, but the purists would say that your CMapEx<> class is
defective in that someone *could* use it with a base class heap pointer and get
potentially undefined behavior.
The rule is that classes intended for derivation should have a virtual
destructor. And the STL containers don't.
Visual C++ MVP