Reputation: 1687
I understand that a function is considered to be constant (bitwise constness) by compiler and if any statement brings modification in the state of object then compiler would throw an error as in Example 1.
Example 1:
class Test
{
public:
int arr[5];
void change(int j) const
{
arr[3]=j;
}
};
int main()
{
Test *ptr=new Test;
ptr->change(3);
}
Example2 :
Now I have declared arr
as an array a pointer, but the following seems to have been working on a few compilers — but on mine it doesn't. Does it mean it has UB? One of the legitimate explanations I came across mentions that we are not directly changing the object hence this is allowed. If so then why UB in my case? I'm using VS2008.
class Test
{
public:
int *arr; //arr is an array
int i;
void change(int j) const
{
arr[3]=j;
}
};
int main()
{
Test *ptr=new Test;
ptr->change(3);
}
Upvotes: 0
Views: 141
Reputation: 58868
First, int *ptr
does not declare ptr
as an array. ptr
is a pointer here.
Second, the reason your code exhibits undefined behaviour is that you're using an uninitialized pointer.
ptr->change(3)
effectively does ptr->arr[3] = 3;
. But you don't know what ptr->arr
points to, so you don't know where you're writing the number 3 to. Maybe it'll point at some unused memory that's safe to overwrite, maybe it'll point to unallocated memory and crash your program as soon as you try to access it, or maybe it'll overwrite something important.
Separately: the reason it compiles is that while arr
is part of the class Test
, *arr
isn't. From inside change
, you can't alter arr
, but you can alter *arr
.
Upvotes: 2