Constant Static Method Modifies Values

I experimented with the const keyword and tried to extract a 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, output 1.5 , I was expecting an error from the compiler, because I have a const method that tries to change the value of the argument.

What am I missing here? How can I create methods that will not change the values ​​of the arguments?

+4
source share
2 answers
  • The method you declared is not const . It returns a const void (whatever it is), but it is not a const method.

  • If it was announced

     void modify(float& dummy) const 

    it would be a const method, but then it could change the value of the argument because it is allowed to use the const method. The only thing that is not allowed to be done is to change the values ​​of the members of the class to which it belongs.

  • Note that to declare the const method, I had to remove the static specification. The static method can never be const , because a static method cannot change any elements in any case.

  • If you want the function to not change its argument, you need 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, he cannot change the member, but he can change the value of his argument. If you want to prevent this, you need to make a const argument:

 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 } }; 
+5
source

You do not understand what const does in this case and how it works.

First of all, in C ++, static member functions cannot be const. The function you show returns a type of "const void" (does it make sense and should the compiler warn - this is another topic).

Secondly, the parameter you are changing is not a constant. If β€œchange” is not a static function and has a β€œconst” modifier for the function, the dummy can be changed:

 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, enter 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. } 
+1
source

Source: https://habr.com/ru/post/1444993/


All Articles