I'm writing this copy constructor:
//CCtor of RegMatrix
RegMatrix::RegMatrix(const RegMatrix &other){
this-> numRow = other.getRow();
this-> numCol = other.getCol();
//Create
_matrix = createMatrix(other.numRow,other.numCol);
int i,j;
//Copy Matrix
for(i=0;i<numRow; ++i){
for(j=0;j<numCol; ++j){
_matrix[i][j] = other._matrix[i][j];
}
}
}
Is there a problem to initialize numRow, numCol in the initialization list like this: numRow(other.numRow), numCol(other.numCol)
instead of:
this-> numRow = other.getRow();
this-> numCol = other.getCol();
Also, i don't know if there isn't such a problem, is there a problem of calling other classes' object's function in the initialization list, such as:
numRow(other.getRow())
instead of:
this-> numRow = other.getRow();
Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.
An initialization list can be used to explicitly call a constructor that takes arguments for a data member that is an object of another class (see the employee constructor example above). In a derived class constructor, an initialization list can be used to explicitly call a base class constructor that takes arguments.
The most common benefit of doing this is improved performance. If the expression whatever is the same type as member variable x_, the result of the whatever expression is constructed directly inside x_ — the compiler does not make a separate copy of the object.
Conclusion: All other things being equal, your code will run faster if you use initialization lists rather than assignment. Note: There is no performance difference if the type of x_ is some built-in/intrinsic type, such as int or char* or float .
Is there a problem to initialize numRow, numCol in the initialization list [...]?
In general, there's two problems with doing so:
In your concrete example this doesn't matter, so you are safe to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With