Static Members

Static functions and properties are declared in the class body but don't need created instances for their usage.

Static Properties

Static properties store value about the class. The value is specific for the class.

Static properties are declared via the keyword static.

The syntax for declaring static member:

The syntax for setting value to static member is:

Here's an example:

Output:

Couple of things to notice:

  • When an object is created via the parametrized constructor (lines 12 - 20), then the static member value is incremented (due to line 19).
  • At line 26 a value is set to the static member. It happens before the the main function lines 28 - 40 executes.
  • When the static member is printed for the first time (line 31), it's value is 0.
  • After objects were created via the parametrized constructor, it's value has reached 3 - the count of the created objects.

Static Functions

Static functions cannot use non-static class member though declared in class.

They are defined via the keyword static.

Syntax for defining:

Syntax for calling:

Here's an example:

Output: