Static Variables & Static Functions in C++


1️⃣ What is a Static Variable in C++?

A static variable in C++ is a variable that belongs to the class rather than any specific object.
It is shared among all objects of the class and is initialized only once in memory.

🔹 Key Features of Static Variables

Belongs to the class, not an object
Retains value between function calls
Has a default value of 0
Declared using static keyword


2️⃣ Example: Static Variable in C++

#include <iostream>
using namespace std;

class Counter {
private:
    static int count;  // Static variable (shared among all objects)

public:
    Counter() {
        count++;  // Increment static variable
    }

    void showCount() {
        cout << "Count: " << count << endl;
    }
};

// Initialize static variable outside the class
int Counter::count = 0;

int main() {
    Counter c1, c2, c3;  // Creating multiple objects

    c1.showCount();
    c2.showCount();
    c3.showCount();

    return 0;
}

🔹 Output

Count: 3
Count: 3
Count: 3

Why is count shared?
All objects share the same count variable, so its value updates globally.


3️⃣ What is a Static Function in C++?

A static function in C++ is a function that belongs to the class rather than an object.

🔹 Key Features of Static Functions

Can only access static variables (because it belongs to the class).
Cannot use this pointer (as it doesn’t belong to an object).
Called using ClassName::functionName()


4️⃣ Example: Static Function in C++

#include <iostream>
using namespace std;

class Counter {
private:
    static int count;  // Static variable

public:
    Counter() {
        count++;  // Increment count when object is created
    }

    static void showCount() {  // Static function
        cout << "Count: " << count << endl;
    }
};

// Initialize static variable
int Counter::count = 0;

int main() {
    Counter c1, c2, c3;

    // Call static function without creating an object
    Counter::showCount();

    return 0;
}

🔹 Output

Count: 3

Why use a static function?
No need to create an object to call the function.
Efficient for class-wide operations (like counting instances).


5️⃣ Difference Between Static and Non-Static Members

Feature Static Variable Non-Static Variable
Storage Allocated once for the class Allocated per object
Access Shared among all objects Unique for each object
Scope Exists throughout program execution Created and destroyed with object
Initialization Must be initialized outside the class Can be initialized in constructor
Feature Static Function Non-Static Function
Access Can only access static members Can access both static & non-static members
Object Requirement Called using ClassName::functionName() Needs an object to be called
this pointer ❌ Not available ✅ Available

6️⃣ Real-World Example: Static Members in a Bank System

#include <iostream>
using namespace std;

class Bank {
private:
    static int totalAccounts;  // Static variable

public:
    Bank() {
        totalAccounts++;  // Increase count when account is created
    }

    static void showTotalAccounts() {  // Static function
        cout << "Total Bank Accounts: " << totalAccounts << endl;
    }
};

// Initialize static variable
int Bank::totalAccounts = 0;

int main() {
    Bank b1, b2, b3, b4;  // Creating multiple accounts

    // Display total accounts without an object
    Bank::showTotalAccounts();

    return 0;
}

🔹 Output

Total Bank Accounts: 4

Why use static members here?
totalAccounts tracks the number of accounts without needing an object.


7️⃣ Key Takeaways

Static Variables: Shared among all objects, initialized once.
Static Functions: Belong to the class, can only access static members.
Efficient for class-wide properties like counting instances or storing global settings.

Would you like an example with static functions in inheritance? 🚀

Post a Comment

0 Comments