Initialise member array using const

Status
Not open for further replies.

Edward

Well-known member
Hi All,

I'm writing a class to handle storage in the EEPROM for my project. What I'd like to do is use arrays of pointers for the various different variables I'd like stored so that when I come to save data, I can simply iterate through an array rather than run round pulling all the values.
I REALLY don't want to use dynamic memory allocation. The project controls a 2W laser and I'm placing a heavy emphasis on robust code.
I would also not like to waste any memory, either in the program or the EEPROM.

What I would therefore like to do is on construction of my object, tell it how many of each byte it will be storing. I dont want to hard code this incase I need to change the size later or use it in another project.
I just wanted to ask before I did a few hours of coding if the following approach would work, I've only included the relavant code

Code:
// in Logger.h

class Logger
{
    private:
       const byte _numI, _numB, _numD; // size of arrays
       byte* _byteAddrs[_numB]; // arrays of pointers to logged varibles
       int*   _intAddrs[_numI];     
       double* _doubleAddrs[_numD];
       // other bits here
    public:
       Logger(const byte i, const byte b, const byte d) : _numI(i), _numB(b), _numD(d)
       {
           // do other bits here
       }
       // rest of class here
}
// EOF

// main.ino

Logger myLogger(1,2,3);  // create logger to store 1 int, 2 bytes, 3 doubles

/*
   rest of main.ino
*/

//EOF
 
Your code isn't legal C++. The array dimensions need to be compile time constant. What you could do, is use a template like this:

Code:
template<uint8_t _numI, uint8_t _numB, uint8_t _numD>
class Logger {
    private:
       uint8_t* _byteAddrs[_numB]; // arrays of pointers to logged varibles
       int*   _intAddrs[_numI];     
       double* _doubleAddrs[_numD];
       // other bits here
    public:
       Logger() 
       {
           // do other bits here
       }
       // rest of class here
};
// EOF

// main.ino

Logger<1,2,3> myLogger();  // create logger to store 1 int, 2 bytes, 3 doubles

using Logger222 = Logger<2,2,2>;
Logger222 myOtherLogger();

'myLogger' and 'myOtherLogger' have different types; pointers to them are not compatible. If you need that functionality, you must introduce a common parent class.
 
Status
Not open for further replies.
Back
Top