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

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

    The constructor does not specify a return type because it would be redundant: there is no type other than the one being constructed that a constructor could potentially "return". I put "return" in quotes because technically constructors do not return anything: when they are invoked in a static context, they initialize an instance in place; when they are invoked in a dynamic context, it is the operator new that returns something, not a constructor.

    0 讨论(0)
  • 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?

    0 讨论(0)
提交回复
热议问题