File: functionStatic.md

package info (click to toggle)
cppcheck 2.19.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 26,688 kB
  • sloc: cpp: 272,455; python: 22,408; ansic: 8,088; sh: 1,059; makefile: 1,041; xml: 987; cs: 291
file content (64 lines) | stat: -rw-r--r-- 1,674 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# functionStatic

**Message**: The member function 'x' can be static<br/>
**Category**: Readability<br/>
**Severity**: Style<br/>
**Language**: C++

## Description

This checker identifies member functions that do not access any non-static member variables or call any non-static member functions. Such functions can be declared as `static` to indicate that they don't require an object instance to operate.

This warning helps improve code quality by:
- Making the function's independence from object state explicit
- Enabling the function to be called without creating an object instance
- Clarifying the function's scope and dependencies

## Motivation

The motivation of this checker is to improve readability.

## How to fix

Add the `static` keyword to the function declaration to indicate that it doesn't require an object instance.

Before:
```cpp
class Calculator {
public:
    int add(int a, int b) {
        return a + b;  // Only uses parameters
    }

    void printMessage() {
        std::cout << "Hello World" << std::endl;  // Uses no instance data
    }

    bool isValidNumber(int num) {
        return num > 0 && num < 1000;  // Pure function
    }
};
```

After:
```cpp
class Calculator {
public:
    static int add(int a, int b) {
        return a + b;  // Can be called as Calculator::add(5, 3)
    }

    static void printMessage() {
        std::cout << "Hello World" << std::endl;  // Can be called without instance
    }

    static bool isValidNumber(int num) {
        return num > 0 && num < 1000;  // Clearly indicates no state dependency
    }
};
```

## Related checkers

- `functionConst` - for member functions that can be declared const