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
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 an operator [][]
. 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 use operator ()
instead because that operator can have more than one argument:
class Object
{
char ** charMap ;
char& operator ()(int row, int column)
{
return charMap[row][column];
}
};
For more information, see the article in the C++ FAQ Lite.