Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining static members in C++

Tags:

c++

static

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'.

  1. Why is it not allowed in C++ ?

  2. Why are const members allowed to be initialized ?

  3. Does this mean static variables in C++ are not initialized with 0 as in C?

Thanks !

like image 760
dev Avatar asked Aug 21 '10 04:08

dev


People also ask

How do you define a static member?

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.

What are static members in C?

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.

What is static declaration in C?

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.

What is static member example?

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 Answers

(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(); 
like image 103
Eugen Constantin Dinca Avatar answered Sep 23 '22 04:09

Eugen Constantin Dinca