Class management issues

Hello everyone, I'm new to the forum and I'm writing to you for a problem that I can't understand.
I created a class inside a library:

.h

class eep
{
  public:
     eep(byte n);
     void init();
  private:
     byte _n;
};

.cpp

eep::eep(byte n)
{
  EEPROM.begin(n);
  _n=n;
}

*// Init network configuration on EEPROM
void eep::init() {
EEPROM.begin(256);
  Serial.print(_n);
}*

Constructor does not initializes EEPROM. If in setup of .ino launch init(), EEPROM is correctly initialized, but Serial.print(_n); gives 0 and not 256.
For this reason i can't use in init(), the eeprom command EEPROM.begin(_n);
For instance of class in .ino i tried:

eep eep(256);
eep e=eep(256);

either way it doesn't work.
Can you help me?
Thanks in advance!

Would you mind to:

  1. Translate the title in English?
  2. Use code tags (</> button in the editor) when posting code?

What is the value of a byte variable when you try to stuff in the value 256? (Hint: a byte is 8 bits so can only hold 0-255)

256 % 256 == 0

thank you. :wink:

You're right, I'm an idiot. :rofl:
Unfortunately I have extracted this code from thousands of lines of the same and I have not noticed the nonsense.

eep::eep(int n)
{
  EEPROM.begin(n);
  _n=n;
}

// Init network configuration on EEPROM
void eep::init() {
EEPROM.begin(_n);
  Serial.print(_n);
}

Now EEPROM.begin(_n); inside init() works, but if I don't put it in the init() and leave it only in the constructor the eeprom is not initialized.
I'm going crazy! :thinking:

I tried to modify code as follow, and also does not works: eeprom is not initialized.

eep::eep(byte n)
{
  EEPROM.begin(512);
  _n=n;
}

Library objects have a .begin() method because the Arduino runtime is not initialized until AFTER the global constructors are called. If they rely on anything done in the runtime initialization, they put that part in .begin() and require you to call it from setup().

That means calling a .begin() function in an object constructor won't work. Add a .begin() to your object and call the .begin() functions from there.

Note: The EEPROM.begin() doesn't actually do any setup.

    //STL and C++11 iteration capability.
    EEPtr begin()                        { return 0x00; }
    EEPtr end()                          { return length(); } //Standards requires this to be the item after the last valid entry. The returned pointer is invalid.
    uint16_t length()                    { return E2END + 1; }
1 Like

Thanks John, now it's clear to me.

That is not universally true. If you are using an ESP8266 or ESP32, they do a whole lot more.

ONLY for global instances of a class. There is NO problem with constructors in dynamically created objects, whether located on the stack or heap.