Static Attributes

Static attributes allow us to store one value for a variable that is consistent through all instances of a class. Read this article to see how this is implemented.

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.


Static class data


#include <iostream>
using namespace std ;
class Humanoid{
    static int qtyHumans ;
    Humanoid(int) ;
    ~Humanoid() ;
} ;
//initialise static member of Humanoid class
int Humanoid::qtyHumans = 0 ;
Humanoid::Humanoid(int age){
    cout << age << " year old object #" << qtyHumans++ << " created!" << endl ;
    cout << "Object #" << --qtyHumans << " destroyed!"<< endl ;
int main () {
    Humanoid simon(25) ;
    Humanoid penny(32) ;
    Humanoid jimmy(63) ;
    return 0;


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!

Source: Derrick Robinson,
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License.

Last modified: Tuesday, August 31, 2021, 11:31 AM