Using default constructor to set the object attribute to default value in C++

45 Views Asked by At

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.

1

There are 1 best solutions below

0
user12002570 On

The former Event() creates a temporary object of type Event which is then discarded. It has no effect on the current instance this. So we don't see any changes in the member variables in this case. From constructors reference:

Constructors have no names and cannot be called directly.

So constructor can't be explicitly called unlike destructors which can be explicitly called.

Event(); //this has no effect on current instance
*this = Event();  //this has effect on current instance as we're assigning to *this

On the other hand in the latter case, you're explicitly resetting the member variables so you see the changes in those as expected.