Why const member function c




















The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. Values defined with const are subject to type checking, and can be used in place of constant expressions. In C, constant values default to external linkage, so they can appear only in source files. A pointer to a variable declared as const can be assigned only to a pointer that is also declared as const.

You can use pointers to constant data as function parameters to prevent the function from modifying a parameter passed through a pointer. For objects that are declared as const , you can only call constant member functions. This ensures that the constant object is never modified. However, it can alter the values of the data members of the objects passed by reference.

Thus to prevent the member function from modifying the arguments passed to it by reference, the const qualifier can be used with member function arguments in both declaration and definition of the member function. To understand the concept of const member function arguments, consider this example. Example: A program to demonstrate const member function arguments.

Hence, if an attempt is made to alter any data of either w1 the calling object or w2 object passed by reference , a compile-time error is generated. Like member functions and member function arguments, the objects of a class can also be declared as const. They are always allowed to modify an object even if the object itself is constant.

Member functions that are static can't be declared to be const. The const keyword modifies the this pointer that is passed to a member function, but static member functions don't a this pointer since they can be called without an object.

Any non- static member function that does not modify the data members of the object that called it should be declared to be const. Futhermore, any const member function that attempts to change a member variable or call a non-const member function will cause a compiler error to occur.

For example:. This will cause a compiler error. Note that constructors cannot be marked as const. This is because constructors need to be able to initialize their member variables, and a const constructor would not be able to do so. Consequently, the language disallows const constructors.

Make any member function that does not modify the state of the class object const, so that it can be called by const objects. Although instantiating const class objects is one way to create const objects, a more common way to get a const object is by passing an object to a function by const reference.

In the lesson We typically make the reference const in order to ensure the function does not inadvertently change the argument, and to allow the function to work with R-values e.



0コメント

  • 1000 / 1000