C++ Static Members

Static members in C++ are variables or functions that belong to the class itself, rather than to individual objects of the class. These members are shared across all instances of the class and can be accessed without creating an object of the class.

There are two types of use static member

1. Static Member Variable

  • Declared inside the class using the static keyword.
  • Must be defined outside the class (except for constexpr static variables in modern C++).

Syntax:


class ClassName {
public:
    static type variableName; // Static member variable declaration
};

Definition outside the class:


type ClassName::variableName = value;  // Static variable definition outside class

Example:


#include <iostream>
using namespace std;

class MyCounter {
public:
    static int count;  // Static member variable count
};

// Definition of static variable outside the class
int MyCounter::count = 1;

int main() {
    MyCounter obj1;  // create the Object

    // Accessing the static variable without an object
    cout << "call the static variable: " << MyCounter::count << endl;

    return 0;
}

Output:

call the static variable: 1

2. Static Member Function

  • Declared inside the class using the static keyword.
  • Can be called without creating an object of the class.

Syntax:


class ClassName {
public:
    static returnType functionName();  // Static member function declaration
};

call the function outside the class:


returnType ClassName::functionName() {  // Static function definition outside class
    // Function code
}

Example:


#include <iostream>
using namespace std;

class Calculator {
public:
    // Static function to add two numbers
    static int add(int a, int b) {
        return a + b;
    }

    // Static function to subtract two numbers
    static int subtract(int a, int b) {
        return a - b;
    }
};

int main() {
    // Using static functions without creating an object
    int sum = Calculator::add(20, 10);
    int diff = Calculator::subtract(20, 10);

    cout << "Sum: " << sum << endl;       // Output: Sum: 30
    cout << "Difference: " << diff << endl; // Output: Difference: 10

    return 0;
}

Output:

Sum: 30
Difference: 10