pokche pokche - 1 month ago 12
C++ Question

How to overload a parentheses operator for both get and set?

I am trying to overload a getter and setter using parentheses operator. When I try to use

double& my_vector::operator()(size_t index){
return array[index]
}


This single operator overloading works for both the case:

eg:
my_vector(1) = 4.01;
&
double x = my_vector(1);


But now I want to make getter as
const
and setter and
non-const
since I will be using const getter in another const function. I do

getter as
double& my_vector::operator()(size_t index) const;


setter as
double& my_vector::operator()(size_t index);


I get
Error: functions that differ only in their return type cannot be overloaded.

I think I know what the error is talking about but I am not sure how to rectify it.

Answer

Here's a complete example which demonstrates how it works; (You can run this here http://ideone.com/kO0Rf1 )

#include <iostream>
using namespace std;

class my_vector {
public:
    double data[6] = {1,2,3,4,5,6};
    double & operator()(size_t i) {
        std::cout<<"Calling non-const ()"<<std::endl;
        return data[i];
    }
    double operator()(size_t i) const {
        std::cout<<"Calling const ()"<<std::endl;
        return data[i];
    }
};

void withConst(const my_vector &v) {
    double vv = v(0);
    std::cout<<"v(0) = "<<vv<<std::endl;
    // v(0) = 4.0; // Does not compile
}

void withNonConst(my_vector &v) {
    v(0) = 4.0;
    double vv = v(0);
    std::cout<<"v(0) = "<<vv<<std::endl;
}

int main() {
    my_vector vec;
    withConst(vec);
    withNonConst(vec);
    return 0;
}
Comments