shawn
shawn

Reputation: 4223

Order of instantiation of global variables

If I have 2 header files, Test1.h and Test2.h, in which I define classes Test1 and Test2 respectively and instantiate 2 objects of those classes in the header files with them included in main.cpp (Test1.h and Test2.h in that order) which contains the main function, what order will test1 and test2 objects be instantiated in?

// Test1.h

class Test1
{

};

Test1 test1;

// Test2.h
class Test2
{

};

Test2 test2;

// main.cpp

#include "Test1.h"
#include "Test2.h"

int main( int argc, const char * argv [] )
{
        return 0;
}

Upvotes: 0

Views: 312

Answers (1)

Loki Astari
Loki Astari

Reputation: 264361

Because they are both in the same compilation unit (main.cpp)

Thus they are guaranteed to be in the order of declaration.
Because you include the header files in a particular order (which is where the variables are declared for some strange reason).

Thus the order is:

Test1  test1;
Test2  test2;

Note: declaring variables in the header file is a bad idea (they should be declared in the source files). Otherwise you are going to end up with multiple declarations.

Upvotes: 6

Related Questions