Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Static Members in C++

Introduction

In C++, static members are class members that are shared among all objects of the class. A static member is common to all instances of the class and can be accessed without creating an instance of the class. Static members can be either variables or functions.

Static Variables

Static variables are shared among all objects of the class. They are declared using the static keyword. Static variables are initialized only once and retain their value between function calls.

class MyClass {
public:
    static int staticVar;
};

int MyClass::staticVar = 0; // Definition and initialization of static variable.

int main() {
    MyClass obj1;
    MyClass obj2;
    
    obj1.staticVar = 5;
    std::cout << "obj1.staticVar: " << obj1.staticVar << std::endl;
    std::cout << "obj2.staticVar: " << obj2.staticVar << std::endl;
    
    return 0;
}
                

Output:

obj1.staticVar: 5
obj2.staticVar: 5

As shown in the example, changing the value of the static variable staticVar using one object changes it for all objects of the class.

Static Functions

Static functions are functions that can access only static variables. They are declared using the static keyword. Static functions can be called without creating an instance of the class.

class MyClass {
public:
    static int staticVar;
    
    static void staticFunc() {
        std::cout << "Static variable: " << staticVar << std::endl;
    }
};

int MyClass::staticVar = 10; // Definition and initialization of static variable.

int main() {
    MyClass::staticFunc(); // Calling static function without creating an instance
    
    return 0;
}
                

Output:

Static variable: 10

In this example, the static function staticFunc is called without creating an instance of MyClass.

Advantages of Static Members

Static members offer several advantages:

  • They are shared among all objects of the class, saving memory.
  • They can be accessed without creating an instance of the class.
  • They provide a way to have class-wide variables and functions.

Use Cases of Static Members

Static members are often used in situations where a class-wide variable or function is needed. Some common use cases include:

  • Counting the number of instances of a class.
  • Creating utility functions that do not depend on instance variables.
  • Managing class-wide settings or configurations.

Summary

Static members in C++ provide a way to share variables and functions among all instances of a class. They are declared using the static keyword and can be accessed without creating an instance of the class. Static members are useful for class-wide variables and functions, and they offer memory efficiency and ease of access.