-4

As simple as this: I want to specify that a function would not change its pointer argument. How to?

class A {
private:
  int *p;
public:
  void foo (const int *q) {
    p = q;
  }
};

A a;
int b = 3;
int *c = &b;
a.foo(c);

Still not working, thanks for the help!

user180574
  • 5,681
  • 13
  • 53
  • 94
  • 2
    You're accepting a `const int*` argument and trying to save it in a non-`const` variable. The error message is trying to explain this to you, so take a moment to read it more carefully. – tadman Jul 11 '17 at 17:25
  • 1
    Yes you say that the function *itself* will not modify what `q` is pointing to. But then you save it in an non-constant pointer so *other* member functions could modify the data. – Some programmer dude Jul 11 '17 at 17:27
  • 1
    `A = a;` What is this? Your attention to detail is low. – Lightness Races in Orbit Jul 11 '17 at 17:27
  • @Someprogrammerdude, I am just wanting to say that the function is not going to modify q. – user180574 Jul 11 '17 at 17:29
  • 1
    @user180574: First of all you mean `b` not `q`; again, attention to detail. Secondly, "stripping away `const` so that other code can modify it" counts as "will modify". Think of it this way: `foo` said "I don't want a licence to modify `b`" ... so it can't give such a licence to anybody else, either. – Lightness Races in Orbit Jul 11 '17 at 17:31
  • I'm sure your C++ book explains this... – Lightness Races in Orbit Jul 11 '17 at 17:32
  • "Still not working" is not a problem description. – Jesper Juhl Jul 11 '17 at 17:39
  • Possible duplicate of [What is the difference between const int\*, const int \* const, and int const \*?](https://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int-const) – Ryan Haining Jul 11 '17 at 18:47

2 Answers2

1

Okay, you have clarified that you did not intend to add constness to the pointee, but instead to the pointer (and this can of course be safely dropped when copying the pointer). The error message is a good indication that you failed in that goal.

The type to do that is:

int* const

Remember, const applies directly to the left (unless there's nothing there, in which case it applies directly to the right).

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

You are passing in 'foo()' a const pointer, this means that you are telling compiler that you don't want anyone to change the data ponted by the pointer. Therefore, converting a const pointer to a non-const pointer makes no-sense. However, if you really want to do so 'just for fun' then you can workaround this by 'memcpy'.

duong_dajgja
  • 4,196
  • 1
  • 38
  • 65