A pointer to a const object doesn't allow to change the object. For example:
class foo {
public:
int m_data;
foo() : m_data{11} {}
};
void change(const foo *obj)
{
obj -> m_data = 21; // gives error, normal
}
This is fine and normal behavior.
What I don't understand is that when we add an additional pointer variable, either of the same type (like foo *
) or of some other type (like bar *
), but not the basic types like int *
, then we can change the value that the pointer points to (from a pointer to the const type itself).
How is this possible?
class foo {
public:
int m_data;
foo *m_next;
foo() : m_data{11}, m_next{nullptr} {}
};
void change(const foo *obj)
{
obj -> m_next -> m_data = 21; // does not give any error! why?
}
This also happens if we take some other type inside foo
, like bar *
.
Why is this happening? How can I define the function so that I can be sure that my function can't change the value the object is pointing to?