There is a “style” (Protocol? Approach? Characteristic?) of C++ programming in the Arduino environment which I don't understand and find very annoying. I've encountered it with Serial, SD, Wire – almost all of the standard libraries.
This tendency is to automatically instantiate an instance of a class (or classes) simply by including its corresponding '.h' file. Want a serial port in your project? Just include Serial.h, you automatically have an instance of the SerialClass in your code. Want a card reader in your system? Just include SD.h. You've automatically got an instance of the SDClass in your code. One doesn't even have to declare it, it's 'just there' in the background, as every Arduino programmer knows (or maybe they don't?) when they begin their project code with Serial.begin() without ever having to declare an instance of the SerialClass.
I can understand that from the point of view of 'simplicity', 'easy to learn', etc. this may be desirable. As long as one is writing short and simple projects in a functional programming style, it's acceptable. But when you graduate to larger and more complex OO projects using C++ (or Objective-C or C# or) it's really a nuisance, even an obstacle.
Here is an example. My current project has three SD card readers, i.e., three separate file systems (like having three hard drives). I wrote my own class for everything I need and named it FileSystem, which includes declarations in the header file (FileSystem.h) like:
SDClass *fileSystem;
Sd2Card *memoryCard;
SdVolume *volume;
SdFile *root;
and statements in the constructor in the implementation file (FileSystem.cpp) like:
fileSystem = new SDClass();
memoryCard = new Sd2Card();
volume = new SdVolume();
root = new SdFile();
I instantiate three instances of 'FileSystem':
FileSystem *fs1,*fs2,*fs3;
fs1 = new FileSystem();
fs2 = new FileSystem();
fs3 = new FileSystem();
This is all working BTW. But the annoying part is that the 'invisible' instance of the SDClass which was automatically instantiated by including SD.h IS STILL THERE, unused, taking up memory. How does one delete these 'background' class instances without explicitly messaging 'delete(&SD);'? Who would think of doing that, deleting something you never created?
This is obviously more of a 'philosophy of programming' or 'psychology of programming' issue than something imminently important or pressing. But if anyone out there can explain to me why the Arduino environment is twisted this way I would appreciate hearing your opinion. It runs counter to everything I have learned in my career as a programmer, and I've been programming computers much longer than most of the people who read this forum have been alive. ![]()
Oh, and yes, I'm a little restless, quarantined in Spain because of the virus, so please don't take offense, I'm not trying to bash anybody or anything.