I was experimenting with the const keyword and trying to get an useful approach from it.
#include <iostream>
class A
{
public:
static const void modify(float& dummy)
{
dummy = 1.5f;
}
};
int main(int argc, char* argv[])
{
auto a = 49.5f;
A::modify(a);
std::cout << a << std::endl;
return(0);
}
this code compiles and works, the output is 1.5, I was expecting an error from the compiler because I have a const method that is trying to modify the value of an argument.
What I’m missing here ? How i can design methods that will not modify argument’s values?
The method you declared is not
const. It returns aconst void(whatever that is), but it is not aconst-method itself.If it were declared
it would be a const-method, but then still it could modify the value of the argument, because a const-method is allowed to do this. The only thing it is not allowed to do is to modify values of members of the class it belongs to.
Note that in order to declare a
constmethod, I had to remove thestaticspecification. Astaticmethod can never beconst, because a static method can’t modify any members anyway.If you want to prevent the function from modifying its argument, you’d have to make the argument const:
To illustrate what a const-method can and cannot do, here is a class that has a member, and a const-function:
As you can see, it cannot modify a member, but it can modify the value of its argument. If you want to prevent that, you need to make the argument
const: