If you declared function as class const function, what means that you can't change the class's variables from the function, you can't return an address of class's variable, unless you'll promise that this function returns a non-changeable (const) value.
Inside the const
function, the function looks at the class's variables as const
variables, so when you try to return the address, you actually return const double *
and not double *
as the function requires.
The solution for this case is to return a pointer to const T
:
const double* AddVecElem(int index) const {return &dblvec[index];}
Or, as you mentioned to declare this function as non-const function.
Another solution is to return a non-pointer value (copy of the value), and use void setValue(..)
function to change this class's variable data.
As for double *dblarray
your function doesn't returns the pointer itself, it returns a copy of your variable (pay attention- your function returns double*
and the variable is within the same pointer level- so it returns a copy). It is just like the following example:
private:
int value;
public:
int return_value() const {
return value; // Copy of the const returns - you don't change class's variable data
}
int* return_pointer_value() const {
return &value; // Compiler error - expected int* returns const int*
}
So, if you want to make the pointer situation equals to the vector's one, you should return double**
and not double*
:
double **AddArrElem(int index) const {
return &dblarray; // Compiler error - expected double** returns const double *const*
// (*const)=> for 'dblarray', (*)=> for '&'
}
Then why the vector behave differently? Why you can't returns &dblvec[index]?
As mentioned in @t.niese post, the call to the operator function of vector recognize that it's a const vector, so it automatically returns const double
- let's have a look of this function:
double& AddVecElem(int index) const {
return dblvec[index]; // Compiler error - Expected double returns const double
}
We want to return reference to this variable, but the returned variable is a constant. So when you want to return double*
you actually returns const double*
.
Even when you try to go around and call to vector.data() it returns you const double *
instead of double*
- And this is the difference between the vector and the pointer.
As reference: Can const member function return a non-const pointer to a data member?