What about delete?I can't understand

Hello, I created an object and I want to make it global but its initialization has to happen in setup() so I've come up with the following:

MyObject* obj = NULL;

setup(){
    obj = new MyObject(params);
}

loop(){

    obj->method();

}

problem is that I would need to do a delete too, or at least that is what I'd do in normal c++ programming...it goes the same for arduino?

Phate867:
at least that is what I'd do in normal c++ programming...it goes the same for arduino?

in normal arduino programming you can't benefit too much from dynamic memory management:
loop() is considered to be repeated forever, and there's only very limited RAM.

Thus you rather build your memory consuming objects statically, if possible:

MyObject obj(static_params);

void setup() {
  obj.begin(dynamic_params);
}

void loop() {
   obj.method();
}

problem is that I would need to do a delete too, or at least that is what I'd do in normal c++ programming...it goes the same for arduino?

Well when are you planning to stop using obj?

What most people do is make a static object, and call obj.begin() in setup, where the begin() function does whatever initialization you need.

Mmm...why is dynamic so bad?

why is dynamic so bad?

Because it runs the risk of fragmenting memory.
When memory is measured in tens or hundreds of kilobits (as it is on microcontrollers), fragmentation is a potential killer.

Ok thanks! I'll just go for a static object then :wink:

You don't -have- to delete objects in C++ unless you need the space or perhaps your O/S doesn't clean up well at program exit. And Arduino has no O/S.

Dynamic allocation in 2k ram for heap and stack is why C++ Strings are bad practice for Arduino.