Dynamic cast fails in same function where it was working. Dynamic cast is working before calling commitTransaction and fails after commitTransaction. In commitTransaction, copy operator is called where delete and new operations are performed. Any thoughts as to what is going on here? I read that heap corruption can cause dynamic_cast to fail. Can anyone please explain why this is happening?
#include <iostream>
#include <string>
using namespace std;
#define num 10000
#define numOfWords 10000
class RollbackAllocator
{
public:
int* memBitMap;
RollbackAllocator & operator=(const RollbackAllocator& rollBack)
{
delete[] memBitMap;
if(rollBack.memBitMap)
{
memBitMap = new int[num];
for(int i = 0;i<num;i++)
{
memBitMap[i] = rollBack.memBitMap[i];
}
}
else
{
memBitMap = 0;
}
return *this;
};
void init()
{
memBitMap = new int[num];
}
};
class ResourceAllocator
{
public:
int temp;
virtual int tempMethod(){
temp = 0;
};
};
class KatanaResourceAllocator : public ResourceAllocator
{
public:
RollbackAllocator mIFPBPDUEntryIndexAllocatorNM;
RollbackAllocator mIFPBPDUEntryIndexAllocatorNMShadow;
void commitTransaction()
{
mIFPBPDUEntryIndexAllocatorNMShadow = mIFPBPDUEntryIndexAllocatorNM;
}
};
int main() {
ResourceAllocator * resourceAllocator = new KatanaResourceAllocator();
KatanaResourceAllocator * allocator = dynamic_cast<KatanaResourceAllocator *>(resourceAllocator); //dynamic_cast works fine type().name= P17ResourceAllocator
cout<< " pre allocator=" << allocator;
allocator->mIFPBPDUEntryIndexAllocatorNM.init();
allocator->mIFPBPDUEntryIndexAllocatorNMShadow.init();
allocator->commitTransaction();
allocator = dynamic_cast<KatanaResourceAllocator *>(resourceAllocator); //allocator is null here type().name= P17ResourceAllocator
cout<<" post allocator=" << allocator;
return 0;
}