When does an object's constructor get called when the object is declared as a global?

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?
Last edited on
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.
Last edited on
closed account (E0p9LyTq)
A global is initialized before main starts.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

class Cat
{
public:
   Cat()  { std::cout << "Cat Constructor...\n"; }
   ~Cat() { std::cout << "Cat Destructor...\n"; }
};

Cat global_cat;

int main()
{
   std::cout << "\nstarting main...\n\n";

   Cat* main_cat = new Cat;

   delete main_cat;

   std::cout << "\nending main...\n\n";
}
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.
JayZoom +1

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


Early dynamic initialization and deferred dynamic initialization are explained here:
http://en.cppreference.com/w/cpp/language/initialization#Non-local_variables
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.
Topic archived. No new replies allowed.