Join us on Facebook!
— Written by Triangles on December 10, 2018 • updated on March 08, 2019 • ID 68 —
Pointer, constant pointer, pointer to constant, constant pointer to constant: what else?
This is a topic that always confused me since the beginning: it's time to figure it out for good. In C and C++ you can have pointers that point to objects. But also constant pointers to objects. Or pointers to constant objects. Or even both. What's the real difference?
The easiest way to tackle the const/non-const pointer issue is to find out the different combinations. You have two actors here: the pointer and the object pointed to. How they can interact together:
Let's take a int
as an example. Those different possibilities can be expressed as follows:
int* a; // Pointer to int
const int* a; // Pointer to const int
int* const a; // Const pointer to int
const int* const a; // Const pointer to const int
Now, suppose you have a simple structure defined like this:
struct Object { int x; };
from which you instantiate two objects:
Object* object1 = new Object{1};
Object* object2 = new Object{2};
Let's see what you can do by mixing the four possibilities listed above.
Both the pointer and the object are writable. You can modify the object, e.g. changing its x
value and you can also modify the pointer, e.g. assign it a new object:
Object* object_ptr = object1;
object_ptr = object2; // Modify pointer, OK
object_ptr->x = 40; // Modify object, OK
You can modify the pointer but you can't modify the object:
const Object* object_ptr = object1;
object_ptr = object2; // Modify pointer, OK
object_ptr->x = 40; // Modify object, ERROR
You can't modify the pointer but you can modify the object:
Object* const object_ptr = object1;
object_ptr = object2; // Modify pointer, ERROR
object_ptr->x = 40; // Modify object, OK
You can't do anything here, except for reading the object value:
const Object* const object_ptr = object1; // Const pointer to const object
object_ptr = object2; // Modify pointer, ERROR
object_ptr->x = 40; // Modify object, ERROR
std::cout << object_ptr->x << "\n"; // Read object, OK
StackOverflow - What is the difference between const int, const int const, and int const *?
StackOverflow - Constant pointer vs pointer on a constant value
Your posts have been really useful! I just wanted to tell you that the text explanations on points 2 and 3 are mixed up.
2: Pointer to const object -> should be: "You can modify the pointer but you can't modify the object"
3: Const pointer to object -> should be: "You can't modify the pointer but you can modify the object"
Let me know if that makes sense :)