c++if-statementconstructorstatic-methodsobjectname

How would I create two matrices (all values Ones or values Zeros) using static member functions which call the same constructor?


So basically the way my program works for using a static member function to request a 2x4 matrix of Zeros proceeds as follows:

Matrix Matrix::Zeros (const int noOfRows, const int noOfCols){
    Matrix outZ(noOfRows, noOfCols);
    return outZ;
} //My static Zeros member function

This was referring to my constructor which stores zero values in a 2x4 matrix as follows:

Matrix::Matrix (const int noOfRows, const int noOfCols){

this->noOfRows = noOfRows;
this->noOfCols = noOfCols;

data = new double[noOfRows*noOfCols];
    for(int i=0; i< noOfRows*noOfCols; i++){
        data[i] = 0;
    }
}

My issue is that I want to call this same constructor to request a 2x4 matrix of Ones using the following static member function:

Matrix Matrix::Ones(const int noOfRows, const int noOfCols){
    Matrix outO(noOfRows, noOfCols);
    return outO;
} //My static Ones member function

This obviously returns a 2x4 matrix of Zeros and not Ones. Therefore, I have been trying to figure out a way to have an if statement within my constructor so that it will create a matrix of Zeros or Ones based on the object name I am returning in my static member function i.e.

if(outZ){
    for(int i=0; i< noOfRows*noOfCols; i++){
        data[i] = 0;
    }
}

if(outO){
    for(int i=0; i< noOfRows*noOfCols; i++){
        data[i] = 1;
    }
}

Is this possible or is there a better alternative for implementing this if statement? (I am limited in this format as I need to use the data variable since I use it later during operator<< overloading)


Solution

  • Pass the value as an optional argument.

    Declaration:

    Matrix (const int noOfRows, const int noOfCols, int value = 0);
    

    Implementation:

    Matrix::Matrix (const int noOfRows, const int noOfCols, int value){
       ...
       data[i] = value;
       ...
    } 
    

    Change the implementation of Matrix::Ones to use 1 as the last parameter.

    Matrix Matrix::Ones(const int noOfRows, const int noOfCols){
        Matrix outO(noOfRows, noOfCols, 1);
        return outO;
    }
    

    PS Using const int as argument type does not have any benefits. You can make your code simpler by using just int.

    Matrix (int noOfRows, int noOfCols, int value = 0);
    

    Same suggestion applies to other functions as well.