Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator[][] C++

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?

like image 851
bobobobo Avatar asked Mar 28 '10 14:03

bobobobo


People also ask

What is operator type C?

C language is rich in built-in operators and provides the following types of operators − Arithmetic Operators. Relational Operators. Logical Operators. Bitwise Operators.

What are the 7 types of 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.


2 Answers

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.

like image 80
Konrad Rudolph Avatar answered Nov 15 '22 20:11

Konrad Rudolph


There is no operator [][]: that's two [] operations in a row. You could:

  • Have Object::operator[] return an object of a second class representing a row, which has its own operator[] method that takes a column number;
  • Write a 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.
like image 37
rjh Avatar answered Nov 15 '22 19:11

rjh