I am new to C++. I have class named MyDate. In addition I have a class named Calendar which has a member type of array of pointers to MyDate objects. How should I declare and initialize members of the array to nullptr in the constructor of Calendar?
-
3See if you can avoid having this array of pointers in the first placeM.M– M.M2016年03月07日 20:09:38 +00:00Commented Mar 7, 2016 at 20:09
2 Answers 2
Smart pointers default-initialize to nullptr:
class Calendar
{
std::array<std::unique_ptr<Date>, 42> m_dates;
};
Otherwise, std::array is an aggregate, so an empty braced init list will zero-initialize all scalar fields:
class Calendar
{
std::array<Date *, 42> m_dates {};
};
1 Comment
-Wmissing-field-initializers warning it were perhaps better to use std::array<Date *, 42> m_dates {{nullptr}};Personally, I'd probably do it like this:
class Calendar {
/* Methods: */
Calendar() noexcept
{ for (auto & ptr: m_dates) ptr = nullptr; }
/* Fields: */
/* Array of 42 unique pointers to MyDate objects: */
std::array<MyDate *, 42> m_dates;
};
PS: You might want to consider using smart pointers like std::unique_ptr or std::shared_ptr instead of raw pointers. Then you wouldn't need to explicitly initialize these in the Calendar constructor at all:
class Calendar {
/* Fields: */
/* Array of 42 pointers to MyDate objects: */
std::array<std::unique_ptr<MyDate>, 42> m_dates;
};
EDIT: Without C++11 features, I'd do this:
class Calendar {
/* Methods: */
Calendar()
{ for (std::size_t i = 0u; i < 42u; ++i) m_dates[i] = NULL; }
/* Fields: */
/* Array of 42 unique pointers to MyDate objects: */
MyDate * m_dates[42];
};
6 Comments
std::array<MyDate *, 42> m_dates {}; is much simpler#include <array> for std::array and #include <memory> for std::unique_ptr/std::shared_ptr.nullptr, std::array, and std::unique_ptr/std::shared_ptr are C++11 features, you must use a compiler supporting C++11. If you want to use C++03 or earlier, you should not have used nullptr in the original question, but NULL. In this case the question must be re-tagged etc. I added to my answer an example for earlier versions of C++.