An anonymous object/variable/instance declaration needs to be within a function. The reason C++ won't allow you to have it is that it simply doesn't make sense.
A temporary variable that gets created is more often than not part of a larger expression (and as we know, expressions can only be contained inside functions or member functions). After the particular statement that uses the expression is over, the temporary instance goes out of scope as well and can no longer be used.
Since expressions cannot be placed outside of functions, it simply doesn't make sense to allow the declaration of temporary variables (which are used with expressions) outside of functions.
Lastly, one very important confusion could occur if C++ DID allow this:
- As you know, declaring a temporary instance can occur like this (Assume I have class Game):
- Outside of a function, the compiler will think we are declaring either a new function, or a constructor for a class type (or some other hodgepodge) and it will just get confused and say typename not recognized.
In short, temporary instances and variables can only go into function bodies.
Hope this helped,
Joe