| High Integrity CPP Guideline 3.5.5 | When overloading the subscript operator ('operator[]') implement both const and non-const versions. |
| (QA C++ 2140, 2141) |
| Justification |
Allow the operator to be invoked on both const and non-const objects.
class Array
{
public:
Array()
{
for ( int i = 0; i < Max_Size; ++i )
{
x[ i ] = i;
}
}
int& operator[] ( const int a )
{
std::cout<< "nonconst" << std::endl;
return x[ a ];
}
int operator[] ( const int a ) const
{
std::cout << "const" << std::endl;
return x[ a ];
}
private:
enum { Max_Size = 10 };
int x[ Max_Size ];
};
int main()
{
Array a;
int i = a[ 3 ]; //non-const
a[ 3 ] = 33; //non-const
const Array ca;
i = ca[ 3 ]; //const
ca[ 3 ] = 33; //compilation error
return 0;
}
|
| Reference |
Effective C++ Item 18; |