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

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

    I believe you can call a constructor from a constructor. It will compile and run. I recently saw someone do this and it ran on both Windows and Linux.

    It just doesn't do what you want. The inner constructor will construct a temporary local object which gets deleted once the outer constructor returns. They would have to be different constructors as well or you would create a recursive call.

    Ref: https://isocpp.org/wiki/faq/ctors#init-methods

提交回复
热议问题