1

I am defining a member variable like this:

float m_Colors[4];

In the constructor I want to initialize it like this:

m_Color = {0.0f, 0.0f, 0.0f, 1.0f};

Even though I have done this a million times before on this particular occasion I get the error "too many initializer values". How could on these two very simple lines of code possibly be something wrong? Please englighten me.

3
  • 7
    m_Colors <-> m_Color? Please show your exact code (a minimal reproducible example). Commented Mar 4, 2021 at 18:27
  • 1
    Note that you could do that with a std::array for example, not a C-like array. Commented Mar 4, 2021 at 18:29
  • 1
    You can't use the = syntax in the constructor iirc Commented Mar 4, 2021 at 18:52

3 Answers 3

2

You cannot reinitialize the array again with the initializer syntax (it was already default initialized when the class was constructed).

You can use the use a ctor initializer list to initialize the array when the class is constructed.

struct S 
{
    S( ) 
      :  floats_{ 1.0f, 2.2f, 3.3f, 4.4f } 
    {  }

private:
    float floats_[ 4 ];
};
Sign up to request clarification or add additional context in comments.

Comments

0

If you want use initializer for built in array, you must do when declare it. Otherwise you can use like this in your constructor:

float tmp[] = { 0.0f, 0.0f, 0.0f, 1.0f };
memcpy_s(m_Colors, 4, tmp, 4);

1 Comment

Seems way to complicated but it would do the job. I have chosen to use an initializer list.
0

You can use std::array<...> as datatype for your member. This way you can initialise it with curly-braces and also assign it this way if needed plus you get some additional modern C++ benefits.

#include <array>

class Object
{
public:
    Object() : m_Colors{0.0f, 0.0f, 0.0f, 1.0f}
    {
    }

private:
    std::array<float, 4> m_Colors;
};

If you need to reassign:

void reinit()
{
    m_Colors = {0.0f, 0.0f, 0.0f, 1.0f};
}

Comments

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.