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

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

    No, in C++ you cannot call a constructor from a constructor. What you can do, as warren pointed out, is:

    • Overload the constructor, using different signatures
    • Use default values on arguments, to make a "simpler" version available

    Note that in the first case, you cannot reduce code duplication by calling one constructor from another. You can of course have a separate, private/protected, method that does all the initialization, and let the constructor mainly deal with argument handling.

提交回复
热议问题