avoiding repeated code in initialization lists

Discussion in 'C++' started by cppaddict, Jun 19, 2004.

  1. cppaddict

    cppaddict Guest

    If you have a class with:

    1. Many members

    2. Two or more constructors

    and if you follow the C++ FAQ guidelines of initializing all member
    variables in a contructor initialiazation list, then you might have
    two constructors that repeat much of the same code:

    MyClass() :
    _member1(0),
    _member2(0),
    _member3("default string")
    _member4(0.0)
    ...etc...
    {}

    MyClass(int x, int y) :
    _member1(0),
    _member2(0),
    _member3("default string")
    _member4(0.0)
    ...etc...
    {
    // does some stuff with x and y
    }

    How can you avoid this unnecessary repetition?

    Thanks for any ideas,
    cpp
     
    cppaddict, Jun 19, 2004
    #1
    1. Advertisements

  2. One way is to factor out the common code into another class, usually making
    that other class a base class.

    class MyClassBase
    {
    public:
    MyClassBase() :
    _member1(0),
    _member2(0),
    _member3("default string")
    _member4(0.0)
    {
    }
    protected:
    int _member1;
    int _member2;
    string _member3;
    double _member4;
    };

    class MyClass : public MyClassBase
    {
    public:
    MyClass() {}
    MyClass(int x, int y)
    {
    // do something with x and y
    }
    };

    john
     
    John Harrison, Jun 19, 2004
    #2
    1. Advertisements

  3. You might like using boost::value_initialized<>. It takes care of member default initialization.
     
    Maxim Yegorushkin, Jun 21, 2004
    #3
  4. cppaddict

    AciD_X Guest


    Instead of overloading the constructors, You might consider using default
    parameters. This may or may not be appropriate, depending on how the
    class and the constructors are designed ...
     
    AciD_X, Jun 22, 2004
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.