6

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.

11
  • 1
    const Person *people[10] Commented Oct 1, 2014 at 13:03
  • @NeilKirk, does this not make the array itself const? Or the pointers const? It seems there would be three different ways to declare it depending on which part you want const. Commented Oct 1, 2014 at 13:04
  • 2
    @user83643: Only two different ways, since a const array is the same thing as an array of const elements. An array of const pointers to mutable Person would be Person* const people[10];. Commented Oct 1, 2014 at 13:05
  • 1
    const Person * cannot change the person, but can point to other people. Person *const can change the person, but can't point to anyone else. I feel I could make a joke here, but one eludes me. Putting the pointer into an array doesn't change that property of the pointer. const Person * == Person const * Commented Oct 1, 2014 at 13:05
  • 1
    @kotlomoy: Yes and no. 3.9.3/2: "Any cv-qualifiers applied to an array type affect the array element type, not the array type." but 3.9.3/5: "Cv-qualifiers applied to an array type attach to the underlying element type, so the notation "cv T," where T is an array type, refers to an array whose elements are so-qualified. An array type whose elements are cv-qualified is also considered to have the same cv-qualifications as its elements." Commented Oct 2, 2014 at 12:49

1 Answer 1

10

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];
Sign up to request clarification or add additional context in comments.

2 Comments

I prefer not to be in doubt!
@NeilKirk, I know (so do I). I still think it's a good idea to use a typedef, because when a declaration looks ugly/long/complicated it requires effort to understand (and this will probably hold true for other developers looking at the code in the future).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.