[C++] What are Static Members? | How to Use Variables and Functions Shared by the Entire Class

目次

Introduction

In C++ classes, member variables (data members) usually hold individual values for each object. If you create two objects, car1 and car2, from a Car class, their gas (gasoline level) is managed separately.

However, there are times when you want to manage information shared by the entire class, such as “how many objects have been created in total from this class.” This is where “Static Members” come in.

In this article, I will explain the mechanism and usage of static member variables, which share a single value across the entire class, and static member functions, which can be called without creating an object.

Sample Code Using Static Members

This code defines a Widget class and uses a static member variable objectCount to count the total number of Widget objects created so far.

Complete Code

#include <iostream>

using namespace std;

class Widget {
private:
    int id;

public:
    // 1. "Declaration" of static member variable
    static int objectCount;

    // Constructor
    Widget() {
        // Increment the shared counter every time an object is created
        objectCount++;
        id = objectCount; // Assign a serial number as ID
        cout << "Widget object created. (ID: " << id << ")" << endl;
    }

    // 3. "Declaration" and "Implementation" of static member function
    static void showCount() {
        cout << "Currently, there are a total of " << objectCount << " Widget objects." << endl;
    }
};

// 2. "Definition" and "Initialization" of static member variable
// Must be written outside the class
int Widget::objectCount = 0;


int main() {
    // Static member functions can be called even when no objects exist
    Widget::showCount();

    cout << "\n--- Creating Widget A ---" << endl;
    Widget widgetA;
    Widget::showCount();

    cout << "\n--- Creating Widget B ---" << endl;
    Widget widgetB;
    Widget::showCount();
    
    return 0;
}

Execution Result

Currently, there are a total of 0 Widget objects.

--- Creating Widget A ---
Widget object created. (ID: 1)
Currently, there are a total of 1 Widget objects.

--- Creating Widget B ---
Widget object created. (ID: 2)
Currently, there are a total of 2 Widget objects.

Code Explanation

1. Static Member Variable (static int objectCount;)

  • Declaration: Add static to the beginning of the variable declaration inside the class definition.
  • Property: objectCount does not belong to individual objects like widgetA or widgetB. Instead, it belongs to the single large container called the Widget class. Therefore, no matter which object accesses it, it always refers to the same single objectCount variable.
  • objectCount++ inside Constructor: Since this objectCount is shared, it is incremented every time a Widget object is created, allowing you to accurately count the total number of generated objects.

2. Definition of Static Member Variable (int Widget::objectCount = 0;)

Static member variables must be defined and initialized outside the class definition (usually in the source file) using the scope resolution operator ::. This is a special rule in C++.

3. Static Member Function (static void showCount())

  • Declaration: Add static to the beginning of the function declaration.
  • Call: You can call it directly using the syntax ClassName::FunctionName, like Widget::showCount();, even without creating an object. This is because static member functions are associated with the entire class.
  • Constraint: Inside a static member function, you cannot access normal (non-static) members (like id). This is because the static member function is not tied to a specific object, so it cannot identify “which object’s id” to access.

Summary

In this article, I explained C++ static members.

  • Static Member Variable: A variable shared by the entire class. Used for global state management, such as counting the total number of objects.
  • Static Member Function: A function that can be called without generating an object. Used when operating only on static member variables.

Static members are powerful tools for expressing data and functions related to the concept of the “Class” itself, independent of the state of individual objects.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次