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.
Event();creates a temporary unnamed object and immediately discards it. It cannot modifythisobject fromsetfunction call.Event()is not actually calling the constructor. Is a constructor a function and is it possible to call a constructor. In the latter case, you're explicitly resetting the member variables while in the latterEvent()has no effect on the current object(and its member therefore)*this = Event();?