C++ static Keyword
Example
The value of a static
attribute is shared between instances of a class:
class MyClass {
public:
static int x;
int y;
int sum() {
return x + y;
}
};
int MyClass::x = 5;
int main() {
MyClass myObj1;
myObj1.y = 3;
MyClass myObj2;
myObj2.y = 5;
cout << myObj1.sum() << "\n";
cout << myObj2.sum() << "\n";
return 0;
}
Definition and Usage
The static
keyword is a modifier that makes an attribute or method belong to the class itself instead of to instances of the class. The attribute or method is shared between all instances of the class.
The static
keyword has another use. It allows a variable inside a function to keep its value across multiple function calls as shown in the example below.
More Examples
Example
The static
keyword allows a variable to keep its value after a function ends:
int add(int myNumber) {
static int total = 0;
total += myNumber;
return total;
}
int main() {
cout << add(5) << "\n";
cout << add(2) << "\n";
cout << add(4) << "\n";
cout << add(9) << "\n";
return 0;
}