0

I am trying to overload () operator to assign value into a dynamically allocated 2D array, here is my code --

class test {
    private:
        int** data ; int row, col ;

    public:
        test(int row = 2, int col = 2)  {
            this->row = row ; this->col = col ;
            this->data = new int*[this->row] ;
            for(int i = 0 ; i < this->row ; i++)
                this->data[i] = new int[this->col] ;
        }

        ~test() {
            for(int i = 0 ; i < this->row ; i++)
                delete [] this->data[i] ;
            delete [] this->data ;
        }

        const int operator() (int row, int col) { // read operation
            return this->data[row][col] ;
        }

        int& operator() (int row, int col) { // write operation
            return this->data[row][col] ;
        }

        // for printing
        friend ostream& operator<< (ostream &os, const test &t);
};

In the operator() write operation, I am trying to return the value by reference so that I can assign value like this --

test t(4,4) ;
t(2,2) = 5 ;

But it does not compile, says that I can't do such kind of overloading, so what should be the correct constructs that could be used to achieve t(2,2) = 5 type of statement ?

0

2 Answers 2

5

Your first overload must be in form:

int operator() (int row, int col) const

Not

const int operator() (int row, int col)

And it is not the read operation, it is used when an object of your type is created as const, this overload will be used, if not const, other overload will be used, both for reading and writing.

Sign up to request clarification or add additional context in comments.

Comments

3

You can't have overloads that only differ in return type. In order to get the effect you want, add a const:

int operator() (int row, int col) const {
    return this->data[row][col];
}

And keep the other overload

int &operator(int row, int col) {
    return this->data[row][col];
}

You can overload methods with a const at the end of the method declaration. What this does is the following:

  1. If the object created is a const test, then int operator()(int row, int col) const will be called
  2. If the object created is a test (no const), then int &operator(int row, int col) will be called

2 Comments

Why the downvote? This is the correct reason why the compiler is giving the error! Please explain
your answer does not help, I did not post this to find error in the code, my question was how overload the () operator so that I can do t(2,2) = 5 kind of coding construct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.