C++ Constructors have no return type. Just exactly why?

前端 未结 8 876
孤独总比滥情好
孤独总比滥情好 2021-01-04 14:00

I\'ve Googled this and read many posts, but there are so many different answers that all make logical sense that I was wondering if an expert on the topic could demystify th

8条回答
  •  春和景丽
    2021-01-04 14:11

    That constructors lack a return type -- not even void -- means that you can't call a constructor from your C++ code. And that's the point. Calling a constructor doesn't make sense. Making it illegal to call a constructor eliminates the very possibility of this type of user error.

    Edit

    barnes is right in that the ultimate reason you can't call constructors is that they have no name. (And even this ignores that you can call a constructor indirectly via placement new.)

    Trying again:

    You can't call constructors from your C++ code because constructors don't have a name. Making constructors not have a return type emphasizes to the programmer that constructors are a very different kind of function than other functions. What a constructor actually does return, if it returns anything, is up to the vendor.

提交回复
热议问题