My question is similar to this one, I think, but for C++, not C# (though the same answer may apply to both).
My question is also similar to this one (of which it has been marked a duplicate). The difference, however, is that that question asks about the constructor prototype, whereas mine asks about the constructor definition block.
Consider the following constructor definition block:
template <class T>
SimpleMatrix<T>::SimpleMatrix(int rows, int cols, const T& initVal)
: m_data(rows * cols, initVal)
, m_rows(rows)
, m_cols(cols)
{}
I'm a C++ newbie, and the CallOne() : call_two(), call_three(), call_four() {}
syntax is confusing me.
Is it equivalent to the following code block?
template <class T>
SimpleMatrix<T>::SimpleMatrix(int rows, int cols, const T& initVal)
{
vector <T> m_data(rows * cols, initVal);
m_rows = rows;
m_cols = cols;
}
Note that inside the SimpleMatrix
class definition, m_data
, m_rows
, and m_cols
are declared in the private
block as follows:
private:
int m_rows;
int m_cols;
vector<T> m_data;
NOTE: Whether this question is a duplicate would be grounds for some debate. In technical terms, yes, it is, and I agree with marking it as such. For a complete newbie, however, it may be hard to derive the answer from the duplicate. This answer, plus the duplicate question, create the whole picture.
In loose terms, yet, it is the same.
The first is an initialization list, which initializes each of the variables. The second is assigning values.
To understand why the first is generally superior, we have to understand the second. When we assign to a variable in the constructor, the code must first initialize it with some default value, and then assign the value we wanted to that newly initialized variable. Thus, it takes two steps.
When we use an initialization list, we are initializing the variable with a value of our choosing, instead of a value chosen automatically. Thus, it only takes one step.
It may seem like a pedantic little detail, but every little bit helps when optimizing.
This is the same concept whether it appears in the constructor's header or implementation.