Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant Member Functions

After reading this, it is my understanding that declaring a method as const prevents it from accidentally modifying the class's member variables.

  • Are const methods commonly used?
  • Should they be used for everything that shouldn't modify member variables?
like image 361
Maxpm Avatar asked Jan 14 '11 13:01

Maxpm


People also ask

What is a constant member function in C++?

Declaring a member function with the const keyword specifies that the function is a "read-only" function that doesn't modify the object for which it's called. A constant member function can't modify any non-static data members or call any member functions that aren't constant.

What are constant member functions Mcq?

Explanation: The constant member functions are a special type of member functions. These are intended to restrict any modification in to the values of object which is used to invoke that function. This is done to ensure that there are no accidental modifications to the object. 2.

What are the member functions?

Member functions are operators and functions that are declared as members of a class. Member functions do not include operators and functions declared with the friend specifier. These are called friends of a class. You can declare a member function as static ; this is called a static member function.

What is const member function in Java?

The Java equivalent of const In a language such as C++, the const keyword can be used to force a variable or pointer to be read-only or immutable. This prevents it from being updated unintentially and can have advantages when it comes to thread-safety.


2 Answers

Yes, const should always be used, when appropriate.

It lets your compiler check your application logic, statically asserting const-correctness for free!

Some people even say that const should be the default, and you should be forced to use mutable for what is non-constant.

like image 101
peoro Avatar answered Sep 27 '22 22:09

peoro


I use const extensively to communicate design intent. If I intended that a method was a pure query, and not a modification function, I would both enforce that and communicate it with a 'const' in the signature.

I encourage you to look at Meyer's thoughts on the matter of side-effect-free functions, and the implications that has on enabling testing.

like image 23
gap Avatar answered Sep 27 '22 22:09

gap