I am following two different C++ programming courses. One is a mandatory course from my Physics degree, ROOT-oriented, and one is a course from the Informatics degree I chose on my own.
The problem is, the examples they give for constructors in classes are slightly different.
Let's pick, for example, the default ctor for a class named CDate, containing three ints, one for the day, one for the month, and one for the year. If nothing is passed to initialize the date, it is automatically set to the first of January, 1900.
The slide from the Informatics course gives this example:
CDate::CDate(void){
mDay=1;
mMonth=1;
mYear=1900;
}
While the one from my Physics course gives this:
CDate::CDate():
mDay (1),
mMonth (1),
mYear (1900)
{}
They only put things inside the braces if they have to modify some variables already created outside the braces.
Let's say, for example, we want to create a class representing an histogram, giving the minimum value, the maximum one, the number of bins, and then an array containing the values inside every single bin. The complete constructor would look like this:
histogram::histogram (const int &nBin, const float &min, const float &max):
nBin_p (nBin),
min_p (min),
max_p (max),
binContent_p ( new int[nBin_p] )
{
//initialize to zero the bin content
for (int i = 0; i < nBin_p; ++i)
binContent_p[i] = 0;
}
(the variables with _p are the actual ones of the class, defined as private in the class implementation).
I guess the "better" one is the one by the Informatics, they should know better, right?But still, I wonder, what are in a nutshell the actual differences between the two ways, as slight as they can be? When should I better use one and when the other one, or are they completely equivalent?
The informatics' approach actually sounds very C-derived, they do not take advantage of some C++ "pecularities". They just do some assignments to those member variables.
The physics rather do initialization. At first sight the difference might only seem aesthetic, and probably won't make much of a difference in practice as long as the member variables you are initializing are fundamental types.
But what if you have a member variable that is of an object type and which does not have a void constructor? To invoke a constructor with arguments for that type you can only use the Physics' approach (which is called initialization list, by the way).