2

I'm having some trouble initializing an object with an array in one line, can someone help me figure out the syntax?

The class is below:

struct Matrix4
{
   float mElements[16];
   Matrix4(float mElements[])
   {
       memset(&this->mElements, 0, sizeof(this->mElements));
       for (int i = 0; i < 16; i++)
            this->mElements[i] = mElements[i];
   }
}

I'm trying to initialize it this way:

Matrix4 mMatrix = Matrix4({1,0,0,0, 
    0,1,0,0,
    0,0,1,0,
    0,0,0,1});

The error I get is:

no instance of constructor "Matrix4::Matrix4" matches the argument list 

Thanks,

3
  • You should just take a look at std::array implementation for example Commented Jun 14, 2019 at 20:08
  • Unrelated, that memset is completely pointless. Why zero-fill an array you're about to fill in entirety. Commented Jun 14, 2019 at 20:10
  • Im trying not to change the class, is it possible to initialize an array this way Commented Jun 14, 2019 at 20:10

1 Answer 1

5

If you want to keep using raw arrays, you can instead take a const reference to an array :

struct Matrix4
{
   float mElements[16];
   Matrix4(const float (&mElements)[16])
   {
       for (int i = 0; i < 16; i++)
            this->mElements[i] = mElements[i];
   }
};

Matrix4 mMatrix = Matrix4({1,0,0,0, 
    0,1,0,0,
    0,0,1,0,
    0,0,0,1});

But you should consider using std::array instead, which has more intuitive semantics :

#include <array>

struct Matrix4
{
   std::array<float, 16> mElements;
   Matrix4(const std::array<float, 16> & mElements) :
      mElements(mElements) {}
};

Matrix4 mMatrix = Matrix4({1,0,0,0, 
    0,1,0,0,
    0,0,1,0,
    0,0,0,1});

Notice that you have an aggregate type, so you don't need to provide a constructor :

#include <array>

struct Matrix4
{
   std::array<float, 16> mElements;
};

Matrix4 mMatrix = {1,0,0,0, 
    0,1,0,0,
    0,0,1,0,
    0,0,0,1};
Sign up to request clarification or add additional context in comments.

3 Comments

second option: I would pass the arg by value and move it into mElements. If the receiver takes ownership, pass by value. The caller can than decide wether to copy or move. In your case, a copy is always performed.
@MFnx In principle yes but moving an array of float is the same as copying it.
Yes, but it should be passed by value anyways.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.