#include <iostream>
class Test
{
public:
int* i = nullptr;
int* const X()
{
return i;
}
};
int main()
{
Test c;
int x = 2;
c.i = c.X();
c.i = &x;
*c.i += 2;
}
what does the const change in the int* const X()
function? in my understanding it should return a const pointer so I shouldn't be able to change what it is pointing to. But I initialize i as a non-const pointer int* i = nullptr;
so I can still do something like c.i = &x
. I could delete the const from the function and the code would run the exact same way as before.
To prevent changing pointing-to value of i I would have to initialize i as const-pointer int* const i = nullptr;
like this, but then if I would delete const from the function it still wouldn't change anything anyway. So what's the point of declaring a function that returns a const pointer if it doesn't change anything?