Reputation: 313
I am trying to create a deep copy of a class by overloading the equals operator - however, it does not seem to be working. Any help appreciated!
This is the class I am trying to copy:
class CMap {
public:
int m_nWidth;
int m_nHeight;
char* m_pData;
void setDimensions(int nWidth, int nHeight);
void operator = (CMap* rhs);
};
this is my overloaded operator:
CMap& operator = (const CMap&rhs)
{
if (this == &rhs)
return *this;
memcpy(this -> m_pData, rhs.m_pData, sizeof(char)*rhs.m_nWidth*rhs.m_nHeight);
return *this;
}
and this is the function call in the main. myMap is an array of CMaps.
CMap tempMap;
tempMap.setDimensions(myMap[0].m_nHeight, myMap[0].m_nWidth);
tempMap.m_pData = myMap[0].m_pData;
Upvotes: 0
Views: 1486
Reputation: 14174
const &
parameter, not a pointer, and returns a reference to the object, not anything.Respect the point three, you have done one thing which does not do "true" copying: Using a dynamic array through a pointer. The compiler will only copy the pointer, so you have to write your own operator=
to copy the array by hand (What you are trying in the question).
The easiest solution is: Use a container like std::vector
instead of manual memory management. It has implemented correctly copying and assigment, so yo do not have to write your own operator=
in your class.
Upvotes: 4