DS3231
DS3231 copied to clipboard
DateTime class accepts type-conflicting assignments
Requesting input from C++ experts regarding a puzzling behavior of the DateTime class as defined in this DS3231.h.
In Arduino IDE 1.8.15, at least, the following assignment ("=" operator) compiled and executed without error or any warning related to type mismatch between the LH and RH operands.
#include <DS3231.h>
DateTime myDT;
uint32_t arbitraryInteger = 42;
void setup() {
myDT = arbitraryInteger;
// ...moreover, to make it perfectly clear...
myDT = 42;
}
Meaningless date and time values wwere retrieved from the DateTime instance following such an assignment.
Code writers using this library should exercise care to ensure that only sensible values are assigned to a DateTime instance.
My question for the community is whether -- and how -- the DateTime class can be defined in such a way that the Arduino IDE compiler will reject assignments of values, to a DateTime instance, that are of other, different, incompatible data types.
Perhaps this assignment of int to DateTime is legal because C++ performs an "implicit conversion"? See discussion on StackOverflow, How can the assignment from int to object be possible in C++?.
If that explains it, then should the constructor, DateTime (uint32_t t =0);
be marked "explicit"?
Marking the constructor "explicit" does trigger a compile-time error in this situation.
explicit DateTime (uint32_t t =0);
#include <DS3231.h>
DateTime myDT;
void setup() {myDT = UINT32_MAX;}
void loop() {}
exit status 1 no match for 'operator=' (operand types are 'DateTime' and 'int')
Should we modify the code to mark that constructor as "explicit"?
@IowaDave you are on the right way with explicit.
Is this topic actual? maybee we can discuss.
BR