I have a template class with two functions, extracts shown below;
template<class TYPE, class ARG_TYPE>
int MyClassT<TYPE, ARG_TYPE>::Add(ARG_TYPE newElement)
{
TYPE Element = newElement; <--- TYPE operator= not called, shallow copy
'
'
}
and
template<class TYPE, class ARG_TYPE>
void MyClassT<TYPE, ARG_TYPE>::SetAt(int nIndex, ARG_TYPE newElement)
{
,
,
m_pData[nIndex] = newElement; <--- TYPE operator= is called, deep copy
'
'
}
Why does the first case result in a shallow copy, yet the second case in a deep copy? I'm assuming a copy constructor is being substituted in the first case, but don't see why.
TYPE Element = newElement; <--- TYPE operator= not called, shallow copy
This should call copy-constructor, not operator=()
, as this is not assignment statement. This is initialization.
operator=()
. In assignment, old object is updated with a given value.So, have you defined a copy-constructor for TYPE
?