I'm creating a custom double
list class. I'd like to overload the ()
operator so that I can both access elements and assign values to list elements. These functions appear with return types, double
and double &
, below, respectively in list.h
. However, you can see below when I run main.cpp
, attempting to use both, only the second operator()
is called. I am obviously misunderstanding something -- what is incorrect in my current code, and why is it incorrect?
list.h
#include <iostream>
class list {
public:
// Constructor
list(int length);
// Destructor
~list();
// Element accessors
double operator()(int i) const;
double & operator()(int i);
private:
int length;
double * data;
};
list::list(int length) {
this->length = length;
this->data = new double[length];
}
list::~list() { delete [] this->data; }
double list::operator()(int i) const {
std::cout << "()1" << std::endl;
return this->data[i];
}
double & list::operator()(int i) {
std::cout << "()2" << std::endl;
return this->data[i];
}
main.cpp
#include <iostream>
#include "list.h"
using namespace std;
int main() {
list l(3);
double x;
// Assign to list element. Should print "()2".
l(1) = 3;
// Get list element value. Should print "()1".
x = l(1);
return 0;
}
After compilation, the program prints:
()2
()2
Edit
My problem arose due to the order in which I added the two functions, and some misunderstanding on my part. I first wrote a simple accessor, i.e.:
double list::operator()(int i);
Afterwards, I tried to add a "setter" overload:
double & list::operator()(int i);
At this point the compiler complained. I searched the web, and without really understanding, added a const
keyword after the first function. This stopped the compiler complaints, but then led to the question above. My solution is to eliminate the first overload, i.e., remove:
double operator()(int i) const;