Home >Backend Development >C++ >How to Initialize Static Data Members in C Without Using the Instance Constructor?

How to Initialize Static Data Members in C Without Using the Instance Constructor?

Barbara Streisand
Barbara StreisandOriginal
2024-11-07 20:25:03349browse

How to Initialize Static Data Members in C   Without Using the Instance Constructor?

Static Initialization: A Comprehensive Guide

In object-oriented programming, static data members are shared among all instances of a class. Typically, they are initialized within the instance constructor. However, what if you want to set up static data members without relying on the instance constructor?

To emulate the behavior of static constructors, create a separate class to encapsulate the static data. For example, consider the following class:

class C {
    // read-only, can also be static const
    // should be filled with all characters from 'a' to 'z'
    static std::vector<char> alphabet;
public:
    C() { /* ... */ }
};

To achieve this, define the static data within a separate ordinary class:

class StaticStuff {
    std::vector<char> letters_;
public:
    StaticStuff() {
        for (char c = 'a'; c <= 'z'; c++) {
            letters_.push_back(c);
        }
    }
};

Now, create a static instance of this class within the original class:

class Elsewhere {
    static StaticStuff staticStuff; // constructor runs once, single instance
};

By creating a static instance of the StaticStuff class, you essentially initialize the static data members before any instances of the Elsewhere class are created, effectively mimicking the functionality of a static constructor.

The above is the detailed content of How to Initialize Static Data Members in C Without Using the Instance Constructor?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn