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?
C language is rich in built-in operators and provides the following types of operators − Arithmetic Operators. Relational Operators. Logical Operators. Bitwise Operators.
In Python, there are seven different types of operators: arithmetic operators, assignment operators, comparison operators, logical operators, identity operators, membership operators, and boolean operators.
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.
There is no operator [][]
: that's two []
operations in a row. You could:
Object::operator[]
return an object of a second class representing a row, which has its own operator[]
method that takes a column number;get(int row, int column)
method and use that instead of operator overloading. I'd recommend this unless your object absolutely has to behave like an array.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With