constructors
-
must have the same name as the class (
Matrix for
the example).
-
is automatically called when an object with this class is created
-
typically used to allocate memory and initialize the class
-
multiple definitions are allowed (overloading). The correct
function is determined by the sequence of arguments given (more
about overloading later).
// this one is used when no arguments are given
// ex. Matrix *m = new Matrix;
//
Matrix::Matrix ( void ) {
_nr = _nc = 0;
_array = NULL;
}
// this one is used when two int arguments are given
// ex. Matrix *m = new Matrix ( 4, 5 );
//
Matrix::Matrix ( int nrows, int ncols ) {
_nr = nrows;
_nc = ncols;
_array = new double [ _nr * _nc ];
}