man/checkers/functionConst.md
Message: Technically the member function 'x' can be const
Category: Robustness
Severity: Style (Inconclusive)
Language: C++
This checker identifies member functions that do not modify any member variables and therefore could be declared as const. A const member function promises not to modify the object's state and enables the function to be called on const objects.
The danger is that a const member function is allowed to have side effects outside the object. If you create a member function that formats the hard drive using system calls it might be technically possible to make the function const, but is it "correct"? Using a const object is not supposed to have side effects.
For methods that has no side effects whatsoever; making them const is recommended.
The checker analyzes member functions and detects when:
This warning is marked as inconclusive because while the function can technically be made const, it may not always be "correct".
This warning helps improve code quality by:
The motivation of this checker is to improve robustness by making the code more const-correct.
Add the const keyword after the function signature to indicate that the function does not modify the object's state.
Before:
class Rectangle {
int width, height;
public:
int getWidth() { return width; }
int getHeight() { return height; }
int getArea() { return width * height; }
void printInfo() {
std::cout << "Width: " << width << ", Height: " << height << std::endl;
}
bool isSquare() {
return width == height;
}
void copyDataTo(Rectangle& other) {
other.width = width;
other.height = height;
}
};
After:
class Rectangle {
int width, height;
public:
int getWidth() const { return width; }
int getHeight() const { return height; }
int getArea() const { return width * height; }
void printInfo() const {
std::cout << "Width: " << width << ", Height: " << height << std::endl;
}
bool isSquare() const {
return width == height;
}
void copyDataTo(Rectangle& other) const {
other.width = width;
other.height = height;
}
};
functionStatic - for member functions that can be declared staticconstParameter - for function parameters that can be constconstParameterReference - for reference parameters that can be constconstParameterPointer - for pointer parameters that can be constconstVariable - for local variables that can be constconstVariableReference - for local reference variables that can be const