Вопрос

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.

Это было полезно?

Решение

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.

Другие советы

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.

You don't need to initialize std::list, since its default constructor will be called.

We should normally initializes following:

  1. Built in types, like int, float etc, else they will be initialized with garbage values.
  2. All other user defined types, which don't have any default constructor.

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top