how to call overloaded subscript in a copy constructor?
-
25-06-2021 - |
Question
If I remove const
from the copy constructor MyArray(const MyArray& cArrayInput)
, all is well. Otherwise the following compile error occurs at the line m_paArray[i] = cArrayInput[i]
:
error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const MyArray' (or there is no acceptable conversion).
I know I can use cArrayInput.m_paArray[i]
. But how to use the overloaded subscript function?
class MyArray
{
private:
int m_nLength;
double* m_paArray;
public:
MyArray():m_nLength(0),m_paArray(0)
{
}
// copy constructor
MyArray(const MyArray& cArrayInput)
{
m_nLength = cArrayInput.m_nLength;
m_paArray = new double[m_nLength];
for(int i=0;i<m_nLength;i++)
m_paArray[i] = cArrayInput[i];
}
double& operator[](const int nIndex)
{
assert(nIndex >= 0 && nIndex < m_nLength);
return m_paArray[nIndex];
}
};
Solution
The problem is that you are calling a non-const operator on a const
instance of MyArray
. So you need to provide a const
version of operator[]
:
const double& operator[](const int nIndex) const
{
assert(nIndex >= 0 && nIndex < m_nLength);
return m_paArray[nIndex];
}
Note that you can provide this version in addition to the non-const version.
As an aside, it may be an idea to to something other than call assert
if the index is out of bounds. You could an throw an exception, for example. That gives the caller code the opportunity to at least recover and do something. The std::out_of_range exception is designed for these cases.