When does an object's constructor get called when the object is declared as a global?
For example, if at the end of the .cpp file's class definition, an instance of the class is instantiated as a global variable... Would it's constructor automatically get called before main() or when the object is first referenced/used?
There is some leeway regarding this in the specification. It can get constructed before main is called or constructed later based on some rules. But it is guaranteed to be created and valid by the time you use it.
However, it's generally regarded as bad programming practice to use global variables. I would try to avoid them unless you have to use them.
Don't instantiate the object outside of your main file.
But the answer is: either. The C++ specification (the last time I checked on this particular topic) gives some flexibility. But it will be constructed and ready to use when you actually use it in your program.
I have been misinformed IN SCHOOL of all places. I will correct the misunderstanding. Read the comments below for a correct answer.
I have been informed that, in some instances, it can be constructed later based on more complex rules. I'll go back and look at the specification again, then.
3.6.2 Initialization of non-local variables
...
3.6.2/4 It is implementation-defined whether the dynamic initialization of a non-local variable with static storage duration is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first odr-use (3.2) of any function or variable defined in the same translation unit as the variable to be initialized.
Footnote: A non-local variable with static storage duration having initialization with side-effects must be initialized even if it is not odr-used - IS
And bam. I have been misinformed.
I will correct my understanding, as well as the understanding of the one who originally gave me that information. Sorry for the mistake.