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

前端 未结 8 900
孤独总比滥情好
孤独总比滥情好 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:26

    Assuming constructors could return something, then this has problematic implications for the following function call:

    class Object{ 
        public: 
            bool Object(){ ... };   
            ...
    }      
    
    SomeFun(Object obj){ ... } 
    
    SomeFun(Object());   
    // Ha! SomeFun jokes on an error about a non-Object argument(of type bool), returned  
    // by the anonymous temporary Object()
    

    Preventing constructor functions from returning, facilitates the use of anonymous temporaries, along with many more C++ features. Without such a rule, innocuous statements can become ambiguous:

    Object obj(Object()); 
    // How does the variable obj decide which constructor to call,  
    // based on its argument type?  
    // 
    // Does it call: bool Object::Object(Object&) or  
    //                    Object::Object(bool)(if it exists)? 
    

    The ability for constructors to return a value, complicates the creation of objects - having a single unambiguous type, the class name, in the absence of arbitrary return values, avoids such problems.

    Can readers suggest further examples where C++ idioms are hindered by the absence of such a rule?

提交回复
热议问题