Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overload constructors/functions when declarations/parameters are the same? [closed]

I would like to create a class to manage the matrices and I met problem with the constructor. The aim is to find the shortest way to call a constructor of a Matrix objet knowing that some of the constructors have the same header as staying clear. This is the idea of what I try to get :

Matrix id; // create identity matrix
Matrix scale(x, y, z); // create directly a scale matrix
Matrix translation(x, y, z) // create a translation matrix
...

Here, all the parameters are floats so I cannot overload the constructor, the only thing I see is to use templates but only for those special cases then I don't know what to do.

Solution

Finally I decided to make an abstract class like this :

class _Mat
{
    public :
        virtual ~_Mat(void) = 0;

        // ...
}

class Mat : public _Mat
{
    public :
        Mat(void);
        virtual ~Mat(void);

        class Scale : public _Mat
        {
            public :
                Scale(float x, float y, float z);
                vitual ~Scale(void);

                // ...
        }

        // ...
}

All will be defined into _Mat and the other class will just be usefull for their constructor(s)

Finally, we can call constructors like this :

Mat id;
Mat::Scale scale(2, 2, 2);
// ...
like image 753
zonn Avatar asked Feb 05 '26 19:02

zonn


1 Answers

You could keep it simple and use static member functions:

struct Matrix
{
    // ...

    static Matrix Translate(float x, float y, float z) {/*...*/}
    static Matrix Scale(float x, float y, float z) {/*...*/}
};

// ...

Matrix m = Matrix::Scale(1,2,3);
like image 174
HolyBlackCat Avatar answered Feb 08 '26 23:02

HolyBlackCat