Given the following code:
class TestA
{
private:
char Temp;
public:
char *Ptr;
TestA(){Ptr = NULL; Temp = 'A'; Ptr = &Temp;}
void Function(){Ptr = &Temp; Temp = 'B';}
void operator=(const TestA &ItemCopy)
{
//ItemCopy.Temp = 'N'; //Not permitted
printf("%c!\n",ItemCopy.Temp);
Ptr = ItemCopy.Ptr; //This is okay
*Ptr = 'M'; //This is okay, but it re-assigns ItemCopy.Temp. What?
printf("%c!\n",ItemCopy.Temp);
}
};
int main()
{
TestA Temp1,Temp2;
Temp1.Function();
Temp2 = Temp1;
}
Produces the following:
B
M
Even though ItemCopy is const. Why am I permitted to indirectly modify it or even take a non-const copy of the pointer?
Because
ItemCopyis const,ItemCopy.Ptrhas and effective type ofchar * const. The pointer is const but the item pointed to can be modified. This means that the assignment:is meaningful and allowed (the underlying object is not itself
const), it is also legal to copy the pointer and assign through it as you have done. A direct assignmentItemCopy.Temp = 'M'would not be legal but that doesn’t meant that you can’t modify the variableItemCopy.Tempif there is another non-constaccess path as you have.