Return type of inherited static function

110 views Asked by At

happy new year! I'm relatively new to both C++ and its community, so sorry for any mistake.

I'm implementing a mat (matrix) class with mat static Zeros(const int rows, const int cols) function, with mat return type. I want to implement a subclass sqmat (square matrix) with the same Zeros function, but returning sqmat.

I've come to this solution:

class mat{
private:

    int rows;
    int cols;
    double* data;

public:

    mat(int rows, int cols){
        this -> rows = rows;
        this -> cols = cols;
        data = new double[rows*cols];
    }

    virtual ~mat(){ delete data; }

    static mat Zeros(int rows, int cols){
        mat matrix(rows, cols); 
        matrix.zero();          
        return matrix;
    }

    mat& zero(){
        for(int i = 0; i < rows*cols; i++)
            data[i] = 0;
        return *this;
    }
}

class sqmat : public mat {
public:

    sqmat(int dim) : mat(dim){};

    static sqmat Zeros(int dim){
        sqmat matrix(dim);  
        matrix.zero();          
        return matrix;
    }
}

In other words, I've used a backup member function zero that makes all the calculations, while I've used the static functions in the parent and child classes to handle the return type. This avoids code repetitions, but it doesn't feel right.

This requires, in fact, to create a backup member function for every static function that I want to implement for both the parent and the child classes, only to return the appropriate data type. Is there a more efficient way to handle this?

Unfortunately, both on my textbook and on the internet, polymorphism is explained using void returning functions, and so I don't have many examples.

PS avoid templates or "advanced" methods please

0

There are 0 answers