c-plus-plus
  1. c-plus-plus-static

C++ Object Class static

Syntax

class className {
  static dataType variableName;
  static dataType functionName(arguments);
};

Note: The static keyword is used to define a static member of the class.

Example

#include <iostream>
using namespace std;

class ExampleClass {
  public:
    static int myVariable;
    static void myFunction() {
      cout << "This is a static function." << endl;
    }
};

int ExampleClass::myVariable = 3;

int main() {
  ExampleClass myObj;
  cout << myObj.myVariable << endl;
  cout << ExampleClass::myVariable << endl;
  ExampleClass::myFunction();
  return 0;
}

Output

3
3
This is a static function.

Explanation

  • The static keyword is used to define a static member of the class.
  • Static variables are shared by all objects of the class.
  • Static functions can be called using the class name without the need for an object of the class.

In the example above, we define a ExampleClass with a static variable myVariable and a static function myFunction(). myVariable is initialized to 3. We then create an object myObj of ExampleClass and print the value of myVariable using both the object and the class name. Finally, we call myFunction() using the class name.

Use

Static members of a class can be used for:

  • Storing values or data across all objects of the class.
  • Implementing functionality that does not require an object of the class.

Important Points

  • Static members of a class are shared by all objects of the class.
  • Static functions can be called using the class name without the need for an object of the class.
  • Static members cannot be accessed using non-static member functions.

Summary

Static members of a class are a great way to store values or data across all objects of the class and implement functionality that does not require an object of the class. They are defined using the static keyword and can be accessed using both the object and the class name.

Published on: