Take the class given below as an example, it is basically just an array within a class.
class MyArray{
public:
MyArray(int maxCapacity = 1024){
ptr = new int[maxCapacity];
numOfElements = 0;
}
~MyArray();
private:
int numOfElements; // current number of elements in array
int *ptr; //pointer to the array data
};
What is the best way to implement a copy constructor for such a class.
Me and a friend are having an argument about it.
My belief is that it would require you to have another capacity variable that stores the maxCapacity argument of the constructor, however when given this question in an exam this variable was not included.
My friend believes that performing a copy that creates the new array based off the value of the numOfElements variable (in some arbitrary way) would suffice.
My issue with his suggestion is that this is not strictly a 'deep copy' as I would think a deep copy would imply that the new object is identical in every way except memory location.
Thanks, Dan
What is the best way to implement a copy constructor for such a class.
Well - the algorithm is quite simple. When copying A into B (so doing MyArray A; MyArray B(A)
), the way here is:
A.numOfElements
elements,B.numOfElements
to A.numOfElements
,numOfElements
elements from A.ptr
to B.ptr
(possibly calling memcpy
or - preferably - std::copy
).And taking into account your second concern:
My belief is that it would require you to have another capacity variable that stores the maxCapacity argument of the constructor (...) My friend believes that performing a copy that creates the new array based off the value of the numOfElements variable (in some arbitrary way) would suffice.
Quoting Wikipedia (text emphasized by me):
An object copy is an action in computing where a data object has its attributes copied to another object of the same data type.
So the answer is: yes, it would suffice, since maxCapacity
isn't an attribute of MyArray
. A deep copy is made when you actually copy the contents of one object into another (not just point to existing ones like when doing a shallow copy). In this case, since A
actually stores numOfElements
elements, we can assume that - even if it can contain more - the rest is just rubbish, so we don't need to copy it.
On the other hand - the class is probably improperly designed. When accessing elements of ptr
, there is no way to check if we're accessing the memory we can, or trying to set memory that doesn't belong to us. Since the class itself doesn't store information about the array size, there is no way it can warn us about overflowing (well it can "crash", but that's probably not the best way to design your classes). And although it's a peculiar design, it doesn't interfere with actually copying the contents of MyArray
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments