Prevent pointer from modification.

How can I prevent a pointer variable from modification.

I want to be able to modify and object that is pointed by variable, but pointer cannot be change to point to something else.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class A {
public:
    void hi() {
    }
};

void someFunction(const A *value) {
    value = new A();  //1
    value->hi();      //2
    
}

int main() {
    return 0;
}


#1 overrides the reference
#2 is a compilation error

I actually want opposite. I want to disable ability to change pointer but allow to change the actual object.
Last edited on
I want to disable ability to change pointer but allow to change the actual object.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class A {
public:
    void hi() {
    }
};

void someFunction(A * const value) {
    //value = new A();  //1 fails
    value->hi();      //2 works
    
}

int main() {
    return 0;
}


Reference:
https://isocpp.org/wiki/faq/const-correctness#const-ptr-vs-ptr-const
Last edited on
Topic archived. No new replies allowed.