How to Use the static Keyword in C++

Jinku Hu Feb 02, 2024
  1. Use the static Keyword to Declare Variables With Static Duration in C++
  2. Use the static Keyword to Declare Static Members of Class in C++
How to Use the static Keyword in C++

This guide will explain several methods of how to use the static keyword in C++.

Use the static Keyword to Declare Variables With Static Duration in C++

The static keyword can be used to declare local variables with static duration. Contrary to what the naming might suggest, a local variable with static duration implies that its value stays active in the memory even after the block, where the variable is declared in, goes out of scope.

Basically, these local variables can have their values saved between the function calls where they are defined. Notice that the incrementCount function has a variable called count, which is initialized with the value of 0. The count attribute is allocated in the memory region that’s active until the program terminates. Thus, each call to incrementCount adds a single unit to the given integer.

#include <iostream>

using std::cout;
using std::endl;

int incrementCount() {
  static int count = 0;
  return ++count;
}

int main() {
  for (int i = 0; i < 20; ++i) {
    if (i % 2 == 0) incrementCount();
  }
  cout << incrementCount() - 1 << endl;

  return EXIT_SUCCESS;
}

Output:

10

Use the static Keyword to Declare Static Members of Class in C++

On the other hand, the static keyword is utilized to declare static data members of the class. These members are associated with the class type itself rather than the particular instances of the class. So, if we define a static data member for a given class, every instance of this class type will have the same value for the data member. Unlike having a private member, the former will have a single copy in the memory. The latter feature makes static data members efficient from the class memory footprint standpoint.

The static data members are defined and initialized differently than regular data members. The static members should be declared inside the class and defined outside the class in the associated source file. The static keyword is only used in the declaration inside the class. None of the static data members can be initialized by the constructors, and they can’t be initialized inside the class body unless they have a const integral type. The latter types still need to be defined outside the class body without an initial value specification. The following example demonstrates the simple usage for the static data member name, which gets initialized with the string literal and is later modified with the setNewName function.

#include <iostream>
#include <string>
#include <utility>

using std::cin;
using std::cout;
using std::endl;
using std::string;

class MyClass1 {
 private:
  static string name;
  string nickname;

 public:
  explicit MyClass1(string n) : nickname(std::move(n)){};

  static string getName() { return name; }
  static void setNewName(std::basic_string<char> s) { name = std::move(s); }
  string getNickname() { return nickname; }

  ~MyClass1() = default;
};

string MyClass1::name = "Static name";

int main() {
  MyClass1 m1(string("April"));
  MyClass1 m2(string("Maude"));

  cout << MyClass1::getName() << endl;
  MyClass1::setNewName("New name");
  cout << MyClass1::getName() << endl;

  return EXIT_SUCCESS;
}

Output:

Static name
New name

Alternatively, the class may have the static function members that are not bound to any object, and thus they can’t refer to the this object in their bodies. Generally, these functions don’t need to have separate declaration and definition similar to the static data members, as shown in the following example program. Still, most contemporary style guides will usually require the programmer to decouple the two of them.

#include <iostream>
#include <string>
#include <utility>

using std::cin;
using std::cout;
using std::endl;
using std::string;

class MyClass1 {
 private:
  static string name;
  string nickname;

 public:
  explicit MyClass1(string n) : nickname(std::move(n)){};

  static string getName() { return name; }
  static void setNewName(std::basic_string<char> s) { name = std::move(s); }
  string getNickname() { return nickname; }

  static bool compareStrings(const std::basic_string<char>& s1,
                             const std::basic_string<char>& s2) {
    if (s1 == s2)
      return true;
    else
      return false;
  }

  ~MyClass1() = default;
};

string MyClass1::name = "Static name";

int main() {
  MyClass1 m1(string("April"));
  MyClass1 m2(string("Maude"));

  MyClass1::compareStrings(m1.getNickname(), m2.getNickname())
      ? cout << "strings are equal" << endl
      : cout << "strings are not equal" << endl;

  MyClass1::compareStrings(MyClass1::getName(), MyClass1::getName())
      ? cout << "strings are equal" << endl
      : cout << "strings are not equal" << endl;

  return EXIT_SUCCESS;
}

Output:

strings are not equal
strings are equal
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Related Article - C++ Static