Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ making an array of pointers to const objects

I'm trying to make a non-constant array of non-constant pointers to constant objects. The idea is that I should be able to change what the pointers in the array point to, but what they point to is a constant object.

I'm having problem defining this array (it's an array of pointers to objects of type Person - a custom class). I'm currently declaring the array like so:

Person* people[10];

Also that's not explicitly saying that the pointers point to const Persons. So when I do something like this:

people[i] = &p;

where p is a reference to an object of type const Person, it fails.

like image 803
user83643 Avatar asked Oct 01 '14 13:10

user83643


People also ask

Can you make pointers to const?

A pointer to a const value (sometimes called a pointer to const for short) is a (non-const) pointer that points to a constant value. In the above example, ptr points to a const int . Because the data type being pointed to is const, the value being pointed to can't be changed. We can also make a pointer itself constant.

How do you create an array of pointers?

An array of pointers is an array that consists of variables of pointer type, which means that the variable is a pointer addressing to some other element. Suppose we create an array of pointer holding 5 integer pointers; then its declaration would look like: int *ptr[5]; // array of 5 integer pointer.

How can we declare pointer to constant in C?

We declare a pointer to constant. First, we assign the address of variable 'a' to the pointer 'ptr'. Then, we assign the address of variable 'b' to the pointer 'ptr'. Lastly, we try to print the value of 'ptr'.

Are arrays const pointers?

The name of the array A is a constant pointer to the first element of the array. So A can be considered a const int*. Since A is a constant pointer, A = NULL would be an illegal statement. Arrays and pointers are synonymous in terms of how they use to access memory.


1 Answers

When in doubt ... use typedef (because it's explicit, adds more specialized semantics and avoids the confusion completely):

typedef const Person* PersonCPtr;
PersonCPtr people[10];
like image 105
utnapistim Avatar answered Sep 30 '22 19:09

utnapistim