Reputation: 22947
I have a header file:
class day
{
public:
day(int id);
~day();
private:
int id;
std::list<meeting*> meetings;
};
and in my .cpp file:
#include "day.h"
#include "meeting.h"
day::day(int id) : id(id) { }
Is it necessary to add meetings()
to the constructor's initialization list?
day::day(int id) : id(id), meetings() { }
I am not sure about the rules of initializing objects with constructors. Are all private members objects get initialized even if not explicitly initialized in the constructor? Also, do I need to create a destructor for the list to delete the objects in the list?
Thanks.
Upvotes: 4
Views: 2072
Reputation: 121
You don't need to initialize std::list
, since its default constructor will be called.
We should normally initializes following:
int
, float
etc, else they will be initialized with garbage values.Upvotes: 1
Reputation: 399723
No, it's not needed since default construction is good enough for you.
Likewise, when your object is destroyed it will destroy the list. I don't think, however, that the list automatically will destroy all its contents, so you still need to do that, in your destructor.
Upvotes: 0
Reputation: 73433
No, list
will be empty by default. The question whether you need to delete the objects in the list
in destructor depends on how you are populating the list. If you insert with something like meetings.insert(new meeting())
then yes, you need to delete the objects in the destructor.
Upvotes: 1
Reputation: 258548
No, types that have default constructors are value-initialized by default.
If you ommit id
from the initialization list, it won't be initialized, because it's an int
. However, the std::list
member will.
It has nothing to do with public
/private
.
Also, do i need to create a destructor for the list to delete the objects in the list ?
Only if day
is the owner of those objects. If they are created outside of the class, and just inserted in the class' member, it's likely that the calling context has to handle the destruction.
Upvotes: 5