C++ Tutorial

Class and Object

Reference

Inheritance and Derivation

Polymorphism and Virtual Functions

Operator Overloading

Template

Exception

Object Oriented Advanced

Input/Output Stream

File Operations

Static Member Variable in C++

In this tutorial, we will learn about static member variables in C++. Static member variables are variables that belong to a class rather than an instance of the class. They are shared among all instances of the class and can be accessed directly through the class without creating an object.

  • Defining a static member variable:

To define a static member variable, use the static keyword in the variable declaration inside the class definition:

class MyClass {
public:
    static int staticVar;
};
  • Initializing a static member variable:

Unlike regular member variables, static member variables must be initialized outside the class definition. To do this, use the scope resolution operator :: and the class name:

int MyClass::staticVar = 42;

In this example, we initialize the staticVar static member variable with the value 42.

  • Accessing a static member variable:

You can access a static member variable using the scope resolution operator :: and the class name:

int main() {
    std::cout << "Static variable value: " << MyClass::staticVar << std::endl; // Output: Static variable value: 42
    return 0;
}

In this example, we access the staticVar static member variable without creating an object of the MyClass class.

  • Using static member variables with non-static and static member functions:

Static member variables can be accessed by both non-static and static member functions of the class. Here is an example that demonstrates this:

class MyClass {
public:
    static int staticVar;

    void printStaticVar() {
        std::cout << "Non-static function, static variable value: " << staticVar << std::endl;
    }

    static void printStaticVarStatic() {
        std::cout << "Static function, static variable value: " << staticVar << std::endl;
    }
};

// Initialize the static member variable
int MyClass::staticVar = 42;

int main() {
    MyClass obj;
    obj.printStaticVar(); // Output: Non-static function, static variable value: 42
    MyClass::printStaticVarStatic(); // Output: Static function, static variable value: 42
    return 0;
}

In this example, we define a non-static member function printStaticVar() and a static member function printStaticVarStatic(), both of which access the staticVar static member variable.

That's it for our C++ static member variable tutorial. Understanding static member variables and their usage is essential for creating efficient and modular code. Static member variables can be useful when you need to share data among all instances of a class, such as keeping track of the number of objects created or storing configuration information.

  1. How to declare and define static member variables in C++:

    #include <iostream>
    
    class MyClass {
    public:
        // Declaration of a static member variable
        static int staticVar;
    };
    
    // Definition of the static member variable
    int MyClass::staticVar = 0;
    
    int main() {
        // Accessing the static member variable
        std::cout << "Static variable: " << MyClass::staticVar << std::endl;
    
        return 0;
    }
    
  2. Static vs non-static member variables in C++:

    #include <iostream>
    
    class MyClass {
    public:
        // Non-static member variable
        int nonStaticVar;
    
        // Static member variable
        static int staticVar;
    };
    
    // Definition of the static member variable
    int MyClass::staticVar = 0;
    
    int main() {
        MyClass obj1, obj2;
        obj1.nonStaticVar = 42;
        obj2.nonStaticVar = 30;
    
        obj1.staticVar = 10;
        obj2.staticVar = 20;
    
        std::cout << "Non-static var (obj1): " << obj1.nonStaticVar << std::endl;
        std::cout << "Non-static var (obj2): " << obj2.nonStaticVar << std::endl;
    
        std::cout << "Static var (obj1): " << obj1.staticVar << std::endl;
        std::cout << "Static var (obj2): " << obj2.staticVar << std::endl;
    
        return 0;
    }
    
  3. Static member variables in classes and structures in C++: They can be declared and defined in both classes and structures.

    #include <iostream>
    
    struct MyStruct {
        // Declaration of a static member variable
        static int staticVar;
    
        // Definition of the static member variable
        static int staticVar;
    };
    
    // Definition of the static member variable
    int MyStruct::staticVar = 0;
    
    int main() {
        // Accessing the static member variable
        std::cout << "Static variable: " << MyStruct::staticVar << std::endl;
    
        return 0;
    }
    
  4. Accessing static member variables through static member functions in C++:

    #include <iostream>
    
    class MyClass {
    private:
        static int staticVar;
    
    public:
        // Static member function accessing static member variable
        static void modifyStaticVar() {
            staticVar = 42;
            std::cout << "Modified static variable: " << staticVar << std::endl;
        }
    
        // Declaration of a static member function
        static void staticFunction();
    };
    
    // Definition of the static member variable
    int MyClass::staticVar = 0;
    
    // Definition of the static member function
    void MyClass::staticFunction() {
        modifyStaticVar();
        std::cout << "Static function called." << std::endl;
    }
    
    int main() {
        MyClass::staticFunction();
        return 0;
    }
    
  5. Static member variables and class-level data in C++:

    #include <iostream>
    
    class BankAccount {
    private:
        static double interestRate;
    
    public:
        // Static member function to set interest rate
        static void setInterestRate(double rate) {
            interestRate = rate;
        }
    
        // Static member function to calculate interest
        static double calculateInterest(double balance) {
            return balance * interestRate;
        }
    };
    
    // Definition of the static member variable
    double BankAccount::interestRate = 0.05;
    
    int main() {
        BankAccount::setInterestRate(0.07);
    
        double balance = 1000.0;
        double interest = BankAccount::calculateInterest(balance);
    
        std::cout << "Interest: " << interest << std::endl;
    
        return 0;
    }
    
  6. Static member variables and object-oriented design in C++:

    #include <iostream>
    
    class Player {
    private:
        static int playerCount;
    
    public:
        Player() {
            playerCount++;
        }
    
        // Static member function to get player count
        static int getPlayerCount() {
            return playerCount;
        }
    };
    
    // Definition of the static member variable
    int Player::playerCount = 0;
    
    int main() {
        Player p1, p2, p3;
    
        std::cout << "Total players: " << Player::getPlayerCount() << std::endl;
    
        return 0;
    }
    
  7. Static member variables and encapsulation in C++:

    #include <iostream>
    
    class TemperatureSensor {
    private:
        static double currentTemperature;
    
    public:
        // Static member function to get current temperature
        static double getCurrentTemperature() {
            return currentTemperature;
        }
    
        // Static member function to set current temperature
        static void setCurrentTemperature(double temperature) {
            currentTemperature = temperature;
        }
    };
    
    // Definition of the static member variable
    double TemperatureSensor::currentTemperature = 0.0;
    
    int main() {
        TemperatureSensor::setCurrentTemperature(25.5);
    
        std::cout << "Current temperature: " << TemperatureSensor::getCurrentTemperature() << std::endl;
    
        return 0;
    }
    
  8. Static member variables and inheritance in C++:

    #include <iostream>
    
    class Base {
    public:
        static int baseVar;
    };
    
    // Definition of the static member variable
    int Base::baseVar = 0;
    
    class Derived : public Base {
    public:
        static int derivedVar;
    };
    
    // Definition of the static member variable
    int Derived::derivedVar = 0;
    
    int main() {
        Base::baseVar = 10;
        Derived::derivedVar = 20;
    
        std::cout << "Base variable: " << Base::baseVar << std::endl;
        std::cout << "Derived variable: " << Derived::derivedVar << std::endl;
    
        return 0;
    }
    
  9. Static member variables and the Singleton pattern in C++: A common use case for a static member variable is implementing the Singleton pattern.

#include <iostream>

class Singleton {
private:
    // Static member variable to hold the instance
    static Singleton* instance;

    // Private constructor to prevent instantiation
    Singleton() {}

public:
    // Static member function to access the instance
    static Singleton* getInstance() {
        if (!instance) {
            instance = new Singleton();
        }
        return instance;
    }

    void showMessage() {
        std::cout << "Singleton instance created." << std::endl;
    }
};

// Initialization of the static data member
Singleton* Singleton::instance = nullptr;

int main() {
    Singleton* obj1 = Singleton::getInstance();
    obj1->showMessage();

    Singleton* obj2 = Singleton::getInstance();
    obj2->showMessage();

    return 0;
}
  1. Static member variables and their initialization in C++: Static member variables can be initialized outside the class or structure definition.
#include <iostream>

class MyClass {
public:
    // Declaration of a static member variable
    static int staticVar;
};

// Definition and initialization of the static member variable
int MyClass::staticVar = 42;

int main() {
    // Accessing the static member variable
    std::cout << "Static variable: " << MyClass::staticVar << std::endl;

    return 0;
}