return type of the constructor in C++

后端 未结 3 1711
走了就别回头了
走了就别回头了 2021-01-01 20:17

I know that there is no return type of the constructors in C++

However, the code below compiles right. What is returned by the constructor in the code below?

3条回答
  •  再見小時候
    2021-01-01 20:55

    Nothing is returned from the constructor. The syntax A() is not a constructor call, it creates a temporary object of type A (and calls the constructor in the process).

    You can't call a constructor directly, constructors are called as a part of object construction.

    In your code, during the construction of the temporary the default constructor (the one you defined) is called. Then, during the construction of a, the copy constructor (generated automatically by the compiler) is called with the temporary as an argument.

    As Greg correctly points out, in some circumstances (including this one), the compiler is allowed to avoid the copy-construction and default-construct a (the copy-constructor must be accessible however). I know of no compiler that wouldn't perform such optimization.

提交回复
热议问题