Static (Methods and Variables) - EduardoMSU/OOP-2143 GitHub Wiki

Static Methods and Variables in Object-Oriented Programming (OOP)

In object-oriented programming, static methods and variables are associated with the class itself rather than with any specific instance of the class. This means they can be accessed without creating an instance of the class. Static members are shared by all instances of a class, and they are often used for functionality that should be common to all objects.


Key Characteristics of Static Members

Type Description
Static Variables Belong to the class rather than any specific instance. There is only one copy of the variable for all instances.
Static Methods Can be called on the class itself without needing an instance. Static methods can only access static variables or methods.

Static Variables

Definition:

A static variable is a variable that is shared by all instances of a class. It retains its value between function calls, and there is only one copy of the static variable for all instances.

Example in C++

#include <iostream>
using namespace std;

class Counter {
public:
    static int count;  // Static variable shared by all instances

    Counter() {
        count++;  // Increment the count every time an object is created
    }

    static void displayCount() {
        cout << "Total objects created: " << count << endl;
    }
};

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

int main() {
    Counter obj1;
    Counter obj2;
    Counter obj3;

    // Display the static variable
    Counter::displayCount();  // Outputs: Total objects created: 3

    return 0;
}
⚠️ **GitHub.com Fallback** ⚠️