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:
delete pMyMap;
BOOM! The problem is that std::map has no *virtual* destructor, so the above
statement causes a subtle bug, because the CMapEx destructor is not called.
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
scenario.
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;
void TestPolymorphic()
{
cout << "*** Polymorphic test:" << endl;
CMyMapString *pSomeMap = new CMyMapString;
assert( pSomeMap->size() == 0 );
delete pSomeMap;
}
This will call the destructor.
I was thinking more along the lines of polymorphism like so;
class MyMap2 : public CMapEx<CString>
{
public:
MyMap2()
{
cout << "MyMap2 constructor." << endl;
}
~MyMap2()
{
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?
Thanks
---