Initialize members of a structure, accessed via pointer, in the constructor of a C ++ class

0

Imagine the DateTime class as follows:

datetime.hpp:

#ifndef DATETIME_HPP
#define DATETIME_HPP

#include <ctime>

class DateTime {
    public:
        DateTime();
        DateTime(int, int, int, int, int); 

    private:
        std::tm *date;
};
#endif // DATETIME_HPP

datetime.cpp:

#include "datetime.hpp"

DateTime::DateTime() : date(new std::tm)
{
    //date = new std::tm;
    date->tm_sec    = 0;
    date->tm_min    = 0;
    date->tm_hour   = 0;
    date->tm_mday   = 0;
    date->tm_mon    = 0;
    date->tm_year   = 0;
    date->tm_wday   = 0;
    date->tm_yday   = 0;
    date->tm_isdst  = 0;
    date->tm_gmtoff = 0;
    date->tm_zone   = 0;
}

DateTime::DateTime(int _D, int _M, int _Y, int _h, int _m) : date(new std::tm)
{
    date->tm_sec    = 0;
    date->tm_min    = _m;
    date->tm_hour   = _h;
    date->tm_mday   = _D;
    date->tm_mon    = _M;
    date->tm_year   = _Y-1900;
    date->tm_wday   = 0;
    date->tm_yday   = 0;
    date->tm_isdst  = 0;
    date->tm_gmtoff = 0;
    date->tm_zone   = 0;
}

The code above works as long as I allocate memory in the builder list and define the fields of the structure in the body of the constructor. I'd like to do everything in the builder's startup list, but I'm really having trouble figuring it out.

It would be something like:

: date(new std::tm), date{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}

e:

: date(new std::tm), date{0, _m, _h, _D, _M, _Y-1900, 0, 0, 0, 0, 0}
    
asked by anonymous 27.09.2018 / 16:57

1 answer

1

If date is a private member of your class and its life cycle always follows the instance of class DateTime , I do not see the need to use dynamic allocation to initialize it.

Note that struct tm has a dozen members, initializing it in the builder's start list can degrade the readability of your code, making it difficult to understand and maintain.

I suggest something more readable and less complex, without using the class builder's start list, see:

datetime.hpp :

#ifndef DATETIME_HPP
#define DATETIME_HPP

#include <ctime>

class DateTime {
    public:
        DateTime();
        DateTime( int day, int month, int year, int hours, int minutes ); 

    private:
        std::tm m_date;
};
#endif 

datetime.cpp :

#include <cstring>
#include <ctime>

#include "datetime.hpp"

DateTime::DateTime()
{
    std::memset( &m_date, 0, sizeof(m_date) );
}

DateTime::DateTime( int day, int month, int year, int hours, int minutes )
{
    std::memset( &m_date, 0, sizeof(m_date) );

    m_date.tm_min    = minutes;
    m_date.tm_hour   = hours;
    m_date.tm_mday   = day;
    m_date.tm_mon    = month - 1;
    m_date.tm_year   = year - 1900;
}
    
27.09.2018 / 18:34