I am trying to define a public static variable like this :
public : static int j=0; //or any other value too
I am getting a compilation error on this very line : ISO C++ forbids in-class initialization of non-const static member `j'.
Why is it not allowed in C++ ?
Why are const members allowed to be initialized ?
Does this mean static variables in C++ are not initialized with 0 as in C?
Thanks !
Static members are data members (variables) or methods that belong to a static or a non static class itself, rather than to objects of the class. Static members always remain the same, regardless of where and how they are used.
When the member variables are declared with a static keyword in a class, then it is known as static member variables. They can be accessed by all the instances of a class, not with a specific instance. The member function of a class declared with a static keyword is known as a static method.
A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.
A typical use of static members is for recording data common to all objects of a class. For example, you can use a static data member as a counter to store the number of objects of a particular class type that are created.
(1.) Why is it not allowed in C++ ?
From Bjarne Stroustrup's C++ Style and Technique FAQ:
A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.
(2.) Why are const members allowed to be initialized ?
[dirkgently said it better]
(3.) Does this mean static variables in C++ are not initialized with 0 as in C?
As far as I know, as long as you declare the static member var in a .cpp it will be zero-initialized if you don't specify otherwise:
// in some .cpp int Test::j; // j = int();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With