2

In Java, we can write as following:

public class Demo{
    private int val;
    public Demo(int val){this.val = val;}
    public Demo(){this(0);}
}

However, it does not work in C++:

class Demo{
    private:
       int _val;
    public:
       Demo(int val):_val(val){}
       Demo(){this(0);}
}

How to revise this code?

allen.lao
  • 49
  • 2
  • 7

3 Answers3

8

With C++11, you could use delegate constructor:

Demo():Demo(0){ }
billz
  • 44,644
  • 9
  • 83
  • 100
4
class Demo{
    private:
       int _val;
    public:
       Demo(int val):_val(val){}
       Demo() :_val(0) {}
}

Or

class Demo{
    private:
       int _val;
    public:
       Demo(int val):_val(val){}
       Demo() :Demo(0) {}
}
Veritas
  • 2,150
  • 3
  • 16
  • 40
1

Or this approach which is useful when there are a lot of members to initialise (and before C++11):

class Demo{
    private:
       int _val;
       void Init( int val )
       {
           _val = val;
       }
    public:
       Demo(int val){Init(val);}
       Demo(){Init(0);}
}
acarlon
  • 16,764
  • 7
  • 75
  • 94