In C++, static class members are shared among all instances of a class. They can be accessed without creating an instance of the class and are typically used for values that are common to all instances. Static members are useful for maintaining state information that is shared across all instances of a class.
class Example {
public:
static int staticValue; // Declaration of static member
int instanceValue; // Instance member
Example(int val) : instanceValue(val) {}
static void setStaticValue(int val) {
staticValue = val; // Setting value of static member
}
static int getStaticValue() {
return staticValue; // Getting value of static member
}
};
// Definition of static member
int Example::staticValue = 0;
int main() {
Example::setStaticValue(10); // Setting static member
Example obj1(1);
Example obj2(2);
std::cout << "Static Value: " << Example::getStaticValue() << std::endl; // Accessing static member
std::cout << "Instance Value of obj1: " << obj1.instanceValue << std::endl; // Accessing instance member
std::cout << "Instance Value of obj2: " << obj2.instanceValue << std::endl; // Accessing instance member
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?