I have a custom date class that is constructed in the following way:

date date_file("dates.txt");

I want to put this object into a new class as a private member, e.g

//the mem_data class======================================//
class mem_data { 


  std::vector<reader> mem_store;
  int complete;
  date date_file;


Now that I have declared
date date_file
How can I initialise it?

For instance, if I want to initialize the int complete to zero, I can simply do
complete = 0;

However, date_file is a custom class, so how would I go about initializing the object/calling the constructor?

5 Years
Discussion Span
Last Post by mike_2000_17

The "initialization list" is what you need. This should, in fact, be used to initialize all your data members and base-classes, if possible. Here is a simple example:

mem_data::mem_data(int a,int b,std::string c) : mem_store(a), complete(b), date_file(c) { };

That's it. What is between the colon and the opening { is called the initialization list and it lists constructor calls to all the data members. If you omit a data member from that list, its default constructor is called implicitly (this is why you should prefer to initialize everything in there, because otherwise you get data members to be default-initialized, and then you give them a value, that is redundant and inefficient).

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.