CKTIS / C++
Const-qualified member function
A const qualifier after a member function's parameter list restricts modification of the object through this. It permits calls through const objects, references, and pointers, but does not imply complete freedom from side effects.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
struct X {
int value() const;
};
int X::value() const {
return 42;
}A const-qualified member function places const after its parameter list, for example int value() const;. This applies to functions with an implicit object parameter. The qualifier must also appear in an out-of-class definition: int Counter::value() const. It does not qualify the return type; const int value() means something different. A static function cannot have this qualifier, nor can a function with an explicit object parameter in C++23.
Inside a function of class X qualified only with const, the expression this has type const X*. Ordinary data members cannot be modified through this access path, and functions requiring a non-const object cannot be called through this. However, the function can be called on a non-const object as well as through const X& or const X*, provided other call constraints permit it.
A function can be overloaded as int& value() and const int& value() const. For an ordinary non-const object, the first overload is preferred; for a const object, the second is available. The trailing qualifier therefore participates in overload resolution independently of the return type.
const guarantees neither freedom from side effects nor thread safety. The function can change mutable members, external state, or a modifiable object pointed to by a pointer member. In the example, value() reads the counter through counter, view, and frozen; view.increment() would be a compilation error.
Examples
#include <iostream>
class Counter {
int value_ = 0;
public:
void increment() { ++value_; }
int value() const;
};
int Counter::value() const {
return value_;
}
int main() {
Counter counter;
counter.increment();
const Counter& view = counter;
const Counter frozen;
std::cout << counter.value() << '\n';
std::cout << view.value() << '\n';
std::cout << frozen.value() << '\n';
}Result
1 1 0
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.