7

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();
limlim
  • 357
  • 2
  • 5
  • 10

2 Answers2

11

Is there a problem to initialize numRow, numCol in the initialization list [...]?

In general, there's two problems with doing so:

  1. While initializing objects in the initialization list, the object is not yet fully constructed. Therefore, when you're invoking non-static member functions, you are invoking them on a not yet fully constructed object. If those functions attempt to use any sub-object of the object that has not been constructed, you are invoking Undefined Behavior.
  2. The order of initialization is the order of declaration of the members in the class definition, it is not the order in which they are listed in the initialization list. Therefore you need to pay attention to initialization of members requiring data from other members. (This can be seen as a sub-problem of the previous: using not yet constructed sub-objects.) It is best to avoid such situations, but if they cannot be avoided, add a big, scary comment to where the members are declared in the class' definition, emphasizing the importance of their order.

In your concrete example this doesn't matter, so you are safe to do this.

sbi
  • 219,715
  • 46
  • 258
  • 445
  • 1
    In other words: there's no problem, as long as you're aware of the effects – valdo Oct 10 '10 at 08:43
  • @valdo: Thinking about this, it might be that invoking member functions on a not yet fully constructed object _technically_ causes _UB_ even if those member function do not access any of the not yet constructed members. I'm not sure about this. (In practice, of course, this is safe as long as you do not access any no yet constructed non-POD objects.) – sbi Oct 10 '10 at 08:49
2

No there is no problem actually. Except that be careful that the order of initialization is NOT the order in which you specify initializers in the init-list. The order is the one in which your members have been declared in the class. Other than that potential problem, I see none. HTH

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434