Can I call a constructor from another constructor (do constructor chaining) in C++?

前端 未结 15 2607
暖寄归人
暖寄归人 2020-11-22 01:27

As a C# developer I\'m used to running through constructors:

class Test {
    public Test() {
        DoSomething();         


        
15条回答
  •  半阙折子戏
    2020-11-22 01:45

    In C++11, a constructor can call another constructor overload:

    class Foo  {
         int d;         
    public:
        Foo  (int i) : d(i) {}
        Foo  () : Foo(42) {} //New to C++11
    };
    

    Additionally, members can be initialized like this as well.

    class Foo  {
         int d = 5;         
    public:
        Foo  (int i) : d(i) {}
    };
    

    This should eliminate the need to create the initialization helper method. And it is still recommended not calling any virtual functions in the constructors or destructors to avoid using any members that might not be initialized.

提交回复
热议问题