Reputation: 273
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?
Upvotes: 4
Views: 1970
Reputation: 69967
The method you declared is not const
. It returns a const void
(whatever that is), but it is not a const
-method itself.
If it were declared
void modify(float& dummy) const
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 const
method, I had to remove the static
specification. A static
method can never be const
, 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:
static void modify(const float& dummy)
To illustrate what a const-method can and cannot do, here is a class that has a member, and a const-function:
class A
{
float my_member;
public:
void modify(float& dummy) const
{
my_member = dummy; // attempt to modify member -> illegal
dummy = 1.5f; // modifies a non-const argument -> ok
}
};
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
:
class A
{
float my_member;
public:
void modify(const float& dummy) const
{
my_member = dummy; // attempt to modify member -> illegal
dummy = 1.5f; // attempt to modify a const reference -> illegal
}
};
Upvotes: 5
Reputation: 10613
You are misunderstanding what 'const' does in this case and how it operates.
First of all, in C++ static member functions cannot be const. The function you show returns a type of 'const void' (whether this makes sense and whether the compiler should warn is another topic).
Second of all the parameter you are changing isn't const. If 'modify' wasn't a static function and had a 'const' modifier on the function, dummy could still be modified:
void modify_nonstatic(float &dummy) const
{
dummy = 1.5f; // perfectly fine - dummy isn't a member of
// the class and can be modified
}
If you want the parameter to be const, make the parameter const:
static void modify(const float &dummy)
{
dummy = 1.5f; // fail! you can't modify a const.
}
void modify_nonstatic(const float &dummy)
{
dummy = 1.5f; // fail! you can't modify a const.
}
Upvotes: 1