Knowledgebase
emscom > emscom Help Desk > Knowledgebase

Search help:


Arduino static class members

Solution

Static member variables are shared by all instances of a class.  Each static member defined within a class must be  re-declared and initialised in global scope.

The answer is in the memory footprint created by an instance of a class.

Code:

class MyObject{
    uint8_t aByte;  //one byte of memory
    uint16_t aInt;  //two bytes of memory
};

MyObject anObject;  //create an instance of MyObject


When anObject was instanced, the compiler created a label in memory, with the name anObject.  aByte was the first member and can be presumed to have a relative address of &0000.  One byte is reserved for aByte, thus aInt has the relative address of &0001 and occupies two bytes;

Code:

class  MyObject{
  static byte aByte;
  int aInt;
};

byte MyObject::aByte = 10;  //there can be only one

MyObject anObject;
MyObject anotherObject;


The static declaration tells the compiler that aByte must always have the same address in memory.  There may be multiple instances of the MyObject type but there can be only one instance of aByte.  Thus, when the instances anObject and anotherObject are created, the aByte members are actually references (pointer), to the single instance of aByte.  Hence, the relative address of the aInt member becomes &0002.

Code:

class MyClass {
  public:
    static uint8_t aByte;     //a reference to a byte,  which resolves to type uint8_t*
    uint16_t aInt;
    MyClass(void) {
      MyClass::aByte = 10;    //you can also initialise a static member in the constructor
    }
    
    void foo(void) {         //and methods are references too
      aByte++;
    }
};



 
Was this article helpful? yes / no
Related articles Arduino UDP device control block example
Dynamic Arrays
Article details
Article ID: 70
Category: Arduino
Date added: 30-03-2015 04:08:15
Views: 2021
Rating (Votes): Article rated 3.0/5.0 (2)

 
« Go back

 
Powered by Help Desk Software HESK, in partnership with SysAid Technologies