Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long constructor initialization lists

How do you deal with them? I have some classes (usually classes that hold stats etc.) with some 20+ variable members, and the initialization lists end up very long, extending beyond the page width if I don't manually wrap around. Do you try and break down such classes or do you deal with this in some other way?

It doesn't look very tidy, but sometimes I write the variables in the list on top of each other like so:

myConstructor(var1, var2, var3, ..., varN) :
 member1(var1),
 member2(var2),
 member3(var3),
 ...
 memberN(varN)
like image 397
Kristian D'Amato Avatar asked Jul 03 '10 12:07

Kristian D'Amato


People also ask

What is constructor initialization list?

Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.

Does initializer list call constructor?

An initialization list can be used to explicitly call a constructor that takes arguments for a data member that is an object of another class (see the employee constructor example above). In a derived class constructor, an initialization list can be used to explicitly call a base class constructor that takes arguments.

What is a constructor initializer list and what are its uses?

Constructor is a special non-static member function of a class that is used to initialize objects of its class type. In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual bases and non-static data members.

What is an initialization list C++?

The initializer list is used to directly initialize data members of a class. An initializer list starts after the constructor name and its parameters.


1 Answers

the initialization lists end up very long, extending beyond the page width if I don't manually wrap around

One way is to refactor: for example, instead of passing in 4 primitive variables ("top", "left", "width", and "height"), just pass in one compound variable ("rectangle").

Alternatively, just to do with source code layout:

class Foo
{
    int m_a;
    int m_b;
    int m_c;
public:
    Foo(
        int a,
        int b,
        int c
        )
        : m_a(a)
        , m_b(b)
        , m_c(c)
    {
    }
};
like image 189
ChrisW Avatar answered Sep 20 '22 16:09

ChrisW