OOP destructor without code

Hi,
I have a general question to destructors in programs on arduino controllers where code is in flash memory.

I have a class the constructor of which is instantiating further classes like buttons.
Is it necessary for the destructor of this class to contain code to delete the button instances or is it sufficient just to declare the destructor without further code?

Will need more details and example code. But, generally, it depends if you're instantiating the objects dynamically. If so, you need to delete them in your destructor or use features like smart pointers (eg std::unique_ptr) that do so automatically.

It's best to avoid destroying objects at all on most types of Arduino. Most Arduino have no "garbage collection" process, so creating & destroying objects dynamically will probably result in a fragmented heap, and, not long after, running out of memory. When memory is all used up, there is no error message, your code tries to continue, but weird things start to happen because memory that is in use starts to get overwritten.

Using memory dynamically is a useful technique on PCs/laptops/servers because there are always multiple processes running which can take advantage of memory that gets freed up by other processes that are no longer using it. (And there are garbage collection process that prevent heap fragmentation.)

But on most Arduino and other microcontrollers, there is only ever one process running, so the only reason to destroy objects and free up dynamic memory is when that single process can re-use the memory for other purposes. That is a pretty rare thing in microcontroller applications.

So my answer to your question is no, don't worry about it. And avoid creating objects dynamically. Create them statically, as many as you need or as many as will fit into the Arduino's limited memory. That way, you will know at compile time if the Arduino has enough memory to run your code reliably. If not, find ways to reduce the memory required or upgrade to an Arduino with more memory.

1 Like

It all depends on how furherButtons get constructed. If you create furtherButton instance in the heap memory like 'furtherButton *bp = new furtherButton' then you should also care destroying it yourself. If you declare it in the stack, like 'furtherButton b;' the destructor will be called automatically by the code generated by C++ compiler.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.