Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to initialize a private list class member in a constructor?

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.

like image 709
Michael Avatar asked Oct 30 '25 05:10

Michael


1 Answers

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.

like image 200
Luchian Grigore Avatar answered Oct 31 '25 18:10

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!