C++11: delegating constructors

Too many initializers/constructors

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Sample
{
public:

    Sample() : r(0), i(0)
    {

    }
    
    Sample(double real) : r(real), i(0)
    {

    }
    
    Sample(double real, double img) : r(real), i(img)
    {

    }
    
    Sample(double data[2]) : r(data[0]), i(data[1])
    {

    }
    
    Sample(const Sample&) = default;
    Sample& operator=(const Sample&) = default;
    ~Sample() = default;
    
private:
    double r;
    double i;
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Sample
{
private:
    void Init(double real, double img)
    {
        this->r = real;
        this->i = img;
    }
public:

    Sample()
    {
        Init(0,0);
    }
    
    Sample(double real)
    {
        Init(real,0);
    }
    
    ...
    
};

delegating constructors

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Sample
{
private:
    //
    // delegated constructor
    // it should cover the most general initialization
    // case and all other constructors will then call
    // this one to initialize the object
    //
    Sample(double real, double img) : r(real), i(img)
    {
    }
public:

    Sample() : Sample(0.0)
    {
    }
    
    Sample(double real) : Sample(real,0)
    {
    }
    
    Sample(double data[2]): Sample(data[0], data[1])
    {
    }
    
    Sample(const Sample&) = default;
    Sample& operator=(const Sample&) = default;
    ~Sample() = default;

private:
    double r;
    double i;
};