Example class:
class array
{
private:
int n_MaxLength;
int n_array;
bool Clone (const array& rhs);
bool Destroy ();
public:
array ();
~array ();
array (const array& rhs);
array& operator=(const array& rhs);
...
//Other functions like setmaxlength, setItem and so on.
};
Here is the constructor and destructor:
array ();
{
// start out with an initial size of 10
n_MaxLength = 10;
n_array = new int[10];
}
~array ();
{
delete[] n_array;
n_array = NULL;
}
Here is the copy constructor:
array (const array& rhs)
{
n_MaxLength = rhs.n_MaxLength;
//Allocate space for the dynamic array.
n_array = new int[n_MaxLength];
//Verify that the memory was properly allocated
if (NULL != n_array)
{
//Copy the contents from rhs into this array.
memcpy(n_array, rhs.n_array, sizeof(int) * n_MaxLength);
}
}
Here is the assignment operator:
// the assignment operator always returns a reference to this object (*this) in order
// to allow operations like this to succeed in C++: a = b = c = d;
// Otherwise only this opertion would succeed a = b;
array& operator= (const array& rhs)
{
//Check that rhs is not = to this. If it is simply return. There is no
//sense in trying to copy over ourselves.
if (this == &rhs)
{
return *this;
}
//The test above was performed, because this code will delete the current
//memory in this object. If we are copying to ourselves, the memory will have been
//deleted, and the new values that we copy to ourselves will be garbage.
//Delete Code
delete[] n_array;
n_array = NULL;
//End Delete Code
//Copy Code
//Copy the new values
n_MaxLength = rhs.n_MaxLength;
//Allocate space for the dynamic array.
n_array = new int[n_MaxLength];
//Verify that the memory was properly allocated
if (NULL != n_array)
{
//Copy the contents from rhs into this array.
memcpy(n_array, rhs.n_array, sizeof(int) * n_MaxLength);
}
//End Copy Code
//Return a reference to this pointer.
return *this;
}
Notice that the Delete code in the assignment operator is the same as the delete code in the destructor. And also that the copy code in the copy constructor is the same as the copy code in the assignment operator. When my class get larger, and there are alot of variables to manage, I usuall