Why are static class members the same for all objects?

Why don't we have different copies of static variables for different objects?

+4
source share
7 answers

Because they will be members of the copy .

The main characteristic of static elements is that they are shared by all instances of the class.

+5
source

Since the $ 9.4.2 / 1 section of C ++ Standard (2003) says:

A static data member is not part of a subobject of a class. There is only one copy of the static data element shared by all objects in the class.

Since only the standard decides what C ++ is and what not, since C ++ was developed!

Static elements are more like global objects. The same copy applies to all objects!

See this post for a detailed answer: Static class members occupy memory if an object of this class has not been created?

+5
source

A static member is not associated with a specific instance.

If you need different member values ​​for each instance, you should use instance members (remove the static keyword).

+4
source

By definition, a static object is one that is shared by all instances of the class. Ordinary members do not have this property.

+3
source

This definition is static - there is one copy of the data. It is separately stored, most likely, together with all other static data of the library or application.

+3
source

Because what static means in this context.

+1
source

Since the static elements of a class are stored separately in the BSS section, each instance of the class has the same value.

-1
source

Source: https://habr.com/ru/post/1337648/


All Articles