Understanding Static Members in C++

Static Variables

Static variables are special members in a C++ program that hold a unique significance. They are initialized to zero before the creation of the first object. Here are some key points about static variables:

  • Initialization: Static variables are set to zero by default before any object is created.
  • Singleton Nature: Only one copy of a static variable exists for the entire program.
  • Shared Among Objects: All objects share the same copy of the static variable.
  • Lifetime: The static variable remains in the memory until the end of the program.

Static Functions

Static functions add another layer of uniqueness to the world of C++. Unlike regular member functions, a static function can be called independently of any object. To access a static function, we use the following syntax:

ClassName::staticFunction();

Example

Let's take a look at a simple example to illustrate static members in action:

#include <iostream>
using namespace std;

class StatX {
private:
    int x;

public:
    // Static variable initialization
    static int sum;

    // Constructor creation
    StatX() {
        x = sum++;
    }

    // Static function definition
    static void displaySum() {
        cout << "Result is " << sum << "\n";
    }

    // Regular member function
    void displayNumber() {
        cout << "Number is: " << x << "\n";
    }
};

// Global initialization of the static variable
int StatX::sum;

int main() {
    // Creating objects
    StatX obj1, obj2, obj3, obj4;

    // Displaying numbers for each object
    obj1.displayNumber();
    obj2.displayNumber();
    obj3.displayNumber();
    obj4.displayNumber();

    // Accessing static function without depending on an object
    StatX::displaySum();

    // Accessing the static variable using an object
    cout << "Static variable sum " << obj1.sum;

    return 0;
}

In this example, we define a class StatX with a static variable (sum), a constructor, a static function (displaySum), and a regular member function (displayNumber). The main function demonstrates the usage of static members.

Next Post Previous Post
No Comment
Add Comment
comment url