Why does C ++ involve building + calling functions in the same line?


I'm wondering why C++ (and possibly other languages, I'm not sure) doesn't allow statements like this.

MyObject foo.DoBar();

You would think that the language could understand to construct the object, then call the function. The only reason I can think of this not working is that if the construction of the object failed, the statement would still try to call the function.

What are the reasons why those who help develop and integrate new features into C++ (and possibly other languages) don't allow this?

You can construct an object and immediately call a function on it, you just can't assign the object to a variable if you do so:


A practical reason for this restriction is that the constructor creates the object and the function you're calling could also have a return value, so that you would end up with two values produced by the same statement. Then you would need some special syntax to assign both of these values to variables, something that doesn't happen anywhere else.

And the little convenience that might be gained by directly calling the method isn't that big of an advantage that it would be worth introducing new syntax for it.