I created a class Event
class Event {
char m_event_desc[DESC_LENGTH + 1]; // description of the event
unsigned int m_time; // time when the event starts
unsigned int getHour();
unsigned int getMinute(unsigned int hour);
unsigned int getSecond(unsigned int hour, unsigned int minute);
public:
Event(); // default constructor
void display();
void set(const char* address = nullptr);
};
and wants to know the difference between
void Event::set(const char* address) {
if (address != nullptr && address[0] != '\0') {
// start new event and store that in the current Event object
m_event_desc[0] = '\0';
strcpy(m_event_desc, address);
m_event_desc[strlen(address)] = '\0'; // put null terminator to avoid any additional value after
m_time = time;
}
else {
Event(); // reset the state as the default value
}
}
and
void Event::set(const char* address) {
if (address != nullptr && address[0] != '\0') {
// start new event and store that in the current Event object
m_event_desc[0] = '\0';
strcpy(m_event_desc, address);
m_event_desc[strlen(address)] = '\0'; // put null terminator to avoid any additional value after
m_time = time;
}
else {
// reset the state as the default value
m_event_desc[0] = '\0';
m_time = time;
}
}
The latter worked but I would like to know why the former does not work. I would appreciate if anyone can help me out with this.
The former
Event()creates a temporary object of typeEventwhich is then discarded. It has no effect on the current instancethis. So we don't see any changes in the member variables in this case. From constructors reference:So constructor can't be explicitly called unlike destructors which can be explicitly called.
On the other hand in the latter case, you're explicitly resetting the member variables so you see the changes in those as expected.