Home > database >  Is "overcrowding" a member initializer list a thing?
Is "overcrowding" a member initializer list a thing?

Time:09-26

Let's say I have a class which has many members that do have a default constructor defined, so it's not required to initialize them in initializer list (like in the example below).

Is there a point, where initializing list gets "overcrowded" so much so that it's kinda awkward to read and it's better to assign things in a constructor's body for the sake of readability?

class Foo {
public:
    Foo(const std::vector<Thing>& things) :
        m_Vec1(1.0f, 1.0f, 1.0f), m_Vec2(1.0f, 1.0f, 1.0f), m_Vec3(1.0f, 1.0f, 1.0f),
        m_Vec4(1.0f, 1.0f, 1.0f), m_SomeFile("some/path/to/file.txt"), m_Model("some/path/to/model.obj"),
        m_AnotherVec(1.0f, 1.0f, 1.0f), m_Things(things), m_Size(things.size())
    {}

private:
    vec3f m_Vec1;
    vec3f m_Vec2;
    vec3f m_Vec3;
    vec3f m_Vec4;

    FileClass m_SomeFile;
    Model m_Model;

    vec3f m_AnotherVec;

    std::vector<Thing> m_Things;
    uint32_t m_Size;
};

CodePudding user response:

If you have fixed values which are known at compile-time you can use inline initialization, like in:

vec3f m_Vec1 = { 1.0f, 1.0f, 1.0f };
vec3f m_Vec2 = { 1.0f, 1.0f, 1.0f };
// etc.

CodePudding user response:

You can use whitespace to make "overcrowded" code more readable. Example:

Foo(const std::vector<Thing>& things) :
        m_Vec1(1.0f, 1.0f, 1.0f),
        m_Vec2(1.0f, 1.0f, 1.0f),
        m_Vec3(1.0f, 1.0f, 1.0f),
        m_Vec4(1.0f, 1.0f, 1.0f),
        m_SomeFile("some/path/to/file.txt"),
        m_Model("some/path/to/model.obj"),
        m_AnotherVec(1.0f, 1.0f, 1.0f),
        m_Things(things),
        m_Size(things.size())
    {}

I don't think the readability could be improved by using the constructor body to assign the members after initialisation.


The example can be further simplified by using constants for repeated initalisers, and default member initialisers instead of the member init list:

class Foo {
public:
    Foo(const std::vector<Thing>& things) :
        m_Things(things) {}

private:
    constexpr inline static vec3f default_vec{1.0f, 1.0f, 1.0f};
    vec3f m_Vec1 {default_vec};
    vec3f m_Vec2 {default_vec};
    vec3f m_Vec3 {default_vec};
    vec3f m_Vec4 {default_vec};

    FileClass m_SomeFile {"some/path/to/file.txt"};
    Model m_Model {"some/path/to/model.obj"};

    vec3f m_AnotherVec {default_vec};

    std::vector<Thing> m_Things;
};

Note that I've removed the m_Size member. It's entirely redundant since the size of the vector is stored within the vector.

  • Related