There is const keyword and it is simply to protect an argument of a function form changing. An example:
1 2 3 4
void func(constint& arg)
{
arg++; // ERROR: it is illegal
}
Let we have a class "Type" and function "chg_elem":
1 2 3 4 5 6 7 8 9 10
class Type {
public:
int* array;
};
void chg_elem(const Type& obj)
{
obj.array = {1,2,4}; // ERROR: it is illegal
obj.array[0] = 1; // NOT AN ERROR: why?
}
The quastion is why is line №9 legal and how to protect the array field form changing?
privyet :) The problem stems from the fact that a pointer is not an array.
Line 9 does not change the pointer "array" in any way - it is only changing the data that the pointer is pointing to.
Also, line 8 is not valid syntax, because {...} braces can only be used when initializing the variable, not assigning to it. If you want to make array point to an actual array, you'd have to either point to an already-existing array, or dynamically allocate an array using new[].
One way to fix your immediate problem is to declare your pointer asconstint* array;
yes, it is my mistake, I meant another. Let the code be
1 2 3 4 5 6 7 8 9 10 11
class Type {
public:
int* array;
};
void chg_elem(const Type& obj)
{
int new_array[] = {1,2,3};
obj.array = new_array; // ERROR: it is illegal
obj.array[0] = 1; // NOT AN ERROR: why?
}
It is not suitable for the case - I will not be able to change it at all - not only in "chg_elem" function.
Thank you for help. Can I have an advice how to modify the code to protect everything from changing in "chg_elem"?
Is there a way to make line №17 legal too? The idea is to be sure that function "new_array" can't change anything but function "set_elem" must have the access :)
Very sorry for the confusion. I edited my post after I realized my mistake.
Maybe someone more powerful than me knows a secret, but you're seeing the problem with public access: Any function can do anything it wants to your variable. I don't know of an elegant way to do that without making array be private.
Ok. I get your idea and I am sorry to - not accurate explanation, i tried to simplify. In the real code I need an encapsulated functions that must be invoked without object
1 2
Type::func(const Type& obj) // like this
obj.func(void) // not like this
It is static function as I know. But it cause the problem: can't be sure that the object is really constant... Is it bad programming style? :(