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

前端 未结 15 2501
暖寄归人
暖寄归人 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:36

    Simply put, you cannot before C++11.

    C++11 introduces delegating constructors:

    Delegating constructor

    If the name of the class itself appears as class-or-identifier in the member initializer list, then the list must consist of that one member initializer only; such constructor is known as the delegating constructor, and the constructor selected by the only member of the initializer list is the target constructor

    In this case, the target constructor is selected by overload resolution and executed first, then the control returns to the delegating constructor and its body is executed.

    Delegating constructors cannot be recursive.

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

    Note that a delegating constructor is an all-or-nothing proposal; if a constructor delegates to another constructor, the calling constructor isn't allowed to have any other members in its initialization list. This makes sense if you think about initializing const/reference members once, and only once.

提交回复
热议问题