Hello All,

I am having problems with the operator= and copy constructors in the following
class. I know since I have a pointer as a class member, I need to allocate more
memory so that these pointers don't point to the same address in memory. I'm using
the full class in a CArray, and for the most part it functions. It fails when
the destructor is called because I'm deleteing memory I shouldn't. Can some one
please provide me with the correct way of creating the copy constructor and the
operator= for this class? Or is there a better way to do this???

TIA!


The (basic) header file....

class CUdpPacket : public CObject
{
public:

CUdpPacket(WORD wBufferSize, BYTE *pBuffer);
CUdpPacket();
// copy operator...
CUdpPacket(const CUdpPacket& cpy);
// assignment constructor...
CUdpPacket& operator=(const CUdpPacket& cpy);

virtual ~CUdpPacket();

BYTE *m_pData;
WORD m_BufferSize;
};




The (basic) cpp file....

CUdpPacket::CUdpPacket()
{
if(m_pData)
{
delete m_pData;
m_pData = 0;
}
m_BufferSize = 0;
TRACE("Default Constructor called.\n");
}

CUdpPacket::CUdpPacket(WORD wBufferSize, BYTE *pBuffer)
{
m_BufferSize = wBufferSize;
m_pData = new BYTE[m_BufferSize];
TRACE("Extended Constructor called.\n");
}

// copy constructor...
CUdpPacket::CUdpPacket(const CUdpPacket& cpy)
{
delete m_pData;
m_pData = 0;
m_BufferSize = cpy.m_BufferSize;
m_pData = new BYTE[m_BufferSize];
*m_pData = * cpy.m_pData;
TRACE("Copy Constructor called.\n");
}

// assignment operator
CUdpPacket& CUdpPacket:perator=(const CUdpPacket& cpy)
{
if(this == &cpy)
return *this;

delete m_pData;
m_pData = NULL;
m_BufferSize = cpy.m_BufferSize;
m_pData = new BYTE[m_BufferSize];
*m_pData = * cpy.m_pData;
TRACE("operator= called.\n");
return *this;
}

CUdpPacket::~CUdpPacket()
{
if(m_pData)
{
delete m_pData;
m_pData = 0;
}
m_BufferSize = 0;
TRACE("Destructor called.\n");
}




Regards,

Paul Belikian