I’d like to overload operator[][] to give internal access to a 2D array of char in C++.
Right now I’m only overloading operator[], which goes something like
class Object
{
char ** charMap ;
char* operator[]( int row )
{
return charMap[row] ;
}
} ;
It works ok.. Is it possible to override operator[][] though?
Don’t try to do that – as others have said, overloading
operator []the way you do actually provides the[][]syntax for free. But that’s not a good thing.On the contrary – it destroys the encapsulation and information hiding of your class by turning an implementation detail – the
char*pointer – to the outside. In general, this is not advisable.A better method would be to implement an
operator [,]which takes more than one argument, or indeed anoperator [][]. But neither exists in C++.So the usual way of doing this is to ditch
operator []altogether for more than one dimension. The clean alternative is to useoperator ()instead because that operator can have more than one argument:For more information, see the article in the C++ FAQ Lite.