liveBook · Manning

Static keyword

As explained in 100 C++ Mistakes and How to Avoid Them

The static specifier is a C++ declaration specifier that gives a class member static storage or class-level rather than object-level association, depending on context.

Mistake: leaving helper methods as ordinary instance methods. A method that needs no object state can be misleading when callers must invoke it through an instance. A static class method makes that class-level role explicit and can run without a class instance. section 9.11

Static class methods can access class variables but not object values. In the Rational example, gcd and reduce perform calculations on supplied values, so they do not need access to a particular Rational object. section 9.11

A clearer alternative

A helper can also remain a private instance method when it directly updates the current object. Listing 9.29 keeps reduce as an instance method and moves gcd to a file-level static function, showing that clarity matters more than applying static mechanically. section 9.11

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains access restrictions and compares static helpers with instance methods and free functions through a Rational implementation.
Examples
Uses three Rational implementations to contrast public instance helpers, static private helpers, and a file-level static function.
What it assumes
Assumes basic C++ classes and methods while distinguishing instance state from class-level state.
What you can do after
Evaluate helper methods and choose static class methods, instance methods, or free functions according to their required object state.
How it connects
Connects static class methods with instance methods, class variables, instance variables, helper methods, and free functions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.