Static Attributes

Static attributes refer to the data members of a class that may be required to be declared as static data types. This could be useful, say, if you needed to know how many objects had been created, were in existence, etc.

 

As with other static declarations the keyword static is used prior to the attributes to be made static, which will ensure that only one copy of the static member exists despite how many objects are made from that class.

 

Static data members of a class are also known as "class variables", because there is only one unique value for all the objects of that same class. Their content is not different from one object of this class to another.

 

Thus a static attribute is shared by all objects of the class and is initialised to zero, should no other initialisation be defined.

 

Static attributes also need to be initialised outside of the class, using the double colon :: scope resolution operator to identify which class it belongs to.

 

Compile & Run:

25 year old object #0 created!
32 year old object #1 created!
63 year old object #2 created!
Object #2 destroyed!
Object #1 destroyed!
Object #0 destroyed!

Leave a Reply