I have a class which contains a data member that occasionally needs to be recalculated, though it is likely to be accessed multiple times before a recalculation is needed. I have defined both const and non-const getter methods for the data, and within the getter method I would like to check whether or not the calculation needs to be run, and call the appropriate method if it does. In the non-const getter, I check whether the value is up-to-date, and if not run the calculation before returning the data. Doing the same in the const getter caused the compiler to complain about the this object being a const type while the calculation method is non-const. I was therefore surprised that the code compiles if I simply call the non-const getter within the const getter. Could someone please explain why this works, because I am slightly confused.
class A {
bool isUpToDate=false;
double someData=0;
// Do some calculation
void calcData()
{
someData = doSomeCalc();
isUpToDate = true; // data is now up-to-date
}
// non-const getter
double& data()
{
if(!isUpToDate)
{
// run the calculation only if data is not up-to-date
calcData()
}
return someData;
}
// const getter that doesn't work
const double& data() const
{
if(!isUpToDate)
{
calcData() // compiler error: "this object is type const A but
calcData is non-const"
}
return someData;
}
// const getter that (mysteriously) works
const double& data() const
{
return data(); // why doesn't the compiler complain that data() is non-const?
}
I am sure that this behavior is actually reasonable and well-defined, I am just curious why it works because I don't understand what is happening here. I am using g++ as my compiler with the c++11 standard, in case that is a relevant factor in why this works.