2
#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?

Usitha Indeewara
  • 870
  • 3
  • 10
  • 21

1 Answers1

0

You just have to write the "const" before the type. Note that the position of const specifies what is going to be constant. The code below creates a const pointer to a variable value in certain location. (This is what you did in the function)

   int* const  ptr; 

And the code below makes what you want; a pointer to a const value in certain location

    const int* ptr;

Applied to your code, it would mean:

#include <iostream>

class Test
{
public:
    const int* i = nullptr;
    const int* X()
    {
        return i;
    }
};

int main()
{
    Test c;

    int x = 2;
    
    c.i = c.X();
    c.i = &x;
    *c.i += 2;

}

If you try this, you will notice the compiler will tell you in the last line that "the expression "*c.i" must be modifiable".

  • `You just have to write the "const" before the type.` - More precisely, you just have to write the `const` before the asterisk `*`. See https://stackoverflow.com/a/5503393 – Matt Oct 27 '22 at 20:03