I read somewhere (cannot find the source now) that
MyClass *p1 = new MyClass;
and
MyClass *p2 = new MyClass();
are essentially equivalent, provided that MyClass provides a default constructor. The compiler understands what I want to do and adds the empty parentheses.
If this is the case, why I am not allowed to write
throw MyException;
but have to use
throw MyException();
? (Yep, a question mark at the beginning of a line.)
To add some more confusion, the C++ FAQ suggests that the second usecase (new MyClass()) does not invoke a constructor, but calls function defined with operator() instead.
No it doesn’t; the two expressions aren’t quite equivalent. The difference is in how the objects are are initialised: the first uses default-initialisation, while the second uses value-initialisation. So they are equivalent for classes that define a default constructor; otherwise, the first will leave POD objects uninitialised, while the second will initialise them to zero.
MyException()is an expression that creates a value-initialised temporary object; you can throw that just like you can throw the value of any other suitable expression.MyExceptionisn’t an expression; it’s just a type name. You can only throw the value of an expression, sothrow MyException;is not valid. There’s no way to create a default-initialised temporary.No it doesn’t. It says that a declaration like
List x();declares a function with a return typeList, not (as one might think) a value-initialised object of typeList. It has nothing to do with new-expressions oroperator().