hg_git hg_git - 3 months ago 24
C++ Question

code repeat in overloaded constructor

I've a class with some overloaded constructor and no default constructor. The overloaded constructor essentially do the same things but differ on the

type
of params provided. Let's say I've a class as follows -

struct info {
int one; // must be filled
int two; // can be empty
int three; // can be empty
}

class A {
int a;
double b;
float c;
info I;

public:

A(a,b,c,one) :
a(a),
b(b),
c(c)
{
// some processing
I.one = one;
// some other processing
....
}

A(a,b,c,i) :
a(a),
b(b),
c(c),
I(i)
{
// some processing
// some other processing
....
}

}


The processing and some processing part is repeating and is slightly dependent on certain paths which are frequently edited, forcing us to do same and same changes to both places.

Can this be reduced to same constructor in some way? I was hoping to do something with constructor delegation, but wasn't able to think of a clever way to do this :/

Answer

Can this be reduced to same constructor in some way?

Yes. In C++11 there are delegating constructor.

For example:

class Foo {
public: 
  Foo(char x, int y) {}
  Foo(int y) : Foo('a', y) {} // Foo(int) delegates to Foo(char,int)
};

EDIT:

As requested, take your example:

class A {
 private:
  A (int _a, double _b, float _c) : a(_a),
                                    b(_b),
                                    c(_c) {
    // This constructor does a lots of stuff...
  }

 public:
  A (int _a, double _b, float _c, int _one) : A(_a, _b, _c) {
    I.one = _one
    // This constructor does nothing
    // Because A(_a, _b, _c) already does everything
  }

  A (int _a, double _b, float _c, info _info) : A(_a, _b, _c) {
    I = _info;
    // This constructor does nothing
    // Because A(_a, _b, _c) already does everything
  }
};