Default value: constructor array-parameter

Hello,

is it possible to to something like that:
1
2
3
4
class Mat2f {
public:
  Mat2f(float matrix[2][2] = {{0, 0}, {0, 0}});
};

I want to force a default argument of a 2x2 array containing 0s.

Thanks!
Last edited on
In C++, this is not possible. You cannot pass blocks of memory by value, thus you cannot give one a default value. You can only pass them by address.
Refer to this page for more information on arrays (towards the bottom in your case)
http://www.cplusplus.com/doc/tutorial/arrays/

A possible solution to your problem is to use the default constructor.
Consider the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>

using namespace std;

class Mat2f
{
    float _matrix[2][2];
public:
    Mat2f()
    : _matrix{} //Default initialize to 0.
    {
    }
    Mat2f(float matrix[][2])
    {
        //Copy contents of matrix to _matrix.
        //Otherwise values will be deleted when/if
        //matrix goes out of scope and this instance doesn't.
        //i.e., matrix is passed by address. 
        memcpy(_matrix, matrix, sizeof(_matrix));

    }

    void print()
    {
        for(int i = 0; i < 2; ++i)
        {
            for(int j = 0; j < 2; ++j)
                cout << _matrix[i][j] << " ";
            cout << endl;
        }
    }
};


int main()
{
    cout << "Default matrix: " << endl;
    Mat2f defaultMat;
    defaultMat.print();

    cout << "Copied matrix: " << endl;
    float matr[2][2] = {{5, 2}, {3, 4}};
    Mat2f mat(matr);
    mat.print();
}
Default matrix:
0 0
0 0
Copied matrix:
5 2
3 4


You could go on to overload the constructor again to accept an initializer_list, and so on.
Last edited on
> A possible solution to your problem is to use the default constructor.

Yes. Perhaps in conjunction with an in-class member initializer.

1
2
3
4
5
6
7
8
9
10
struct mat
{
    mat() = default ;

    // other constructors

    // ...

    private: int m[3][4] { {0,1,2,3}, {2,3,4,5}, {4,5,6,7} } ;
};
Last edited on
I did not check such code but maybe it is valid if your compiler supports features of the C++ 2011 Standard

1
2
3
4
class Mat2f {
public:
  Mat2f( const float ( &matrix )[2][2] = {{0, 0}, {0, 0}} );
};



Try it and let know whether this code will be compiled.
Topic archived. No new replies allowed.