What is the difference between a an array being passed as a constant versus the array values being constants?
When passing an array of pointers to a function when every value is a constant:
`void display(Fraction* const ar[], int size);`
everything works fine but when the array is a constant
`void display(const Fraction* ar[], int size);`
the compiler gives the following error when calling the function:
`error C2664: 'display' : cannot convert parameter 1 from 'Fraction *[3]' to 'const Fraction *[]'`
main:
int main()
{
Fraction* fArray[3];
Fraction* fOne = new Fraction();
Fraction* fTwo = new Fraction();
Fraction* fThree = new Fraction();
fOne->num = 8;
fOne->den = 9;
fTwo->num = 3;
fTwo->den = 2;
fThree->num = 1;
fThree->den = 3;
fArray[0] = fOne;
fArray[1] = fTwo;
fArray[2] = fThree;
display(fArray, 3);
system("pause");
return 0;
}
This is a FAQ.
Note that
const T* a[]meansT const* a[], i.e. it’s not the array itself that you have declaredconst; instead you have declared an array of pointers toconstitems.Essentially, if the language provided an implicit conversion
T**→T const**, then you could inadvertently attempt to change something that was originally declaredconst: