Home > Backend Development > C++ > body text

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

Barbara Streisand
Release: 2024-11-07 20:25:03
Original
259 people have browsed it

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() { /* ... */ }
};
Copy after login

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);
        }
    }
};
Copy after login

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!