Question

I am working on a C++ project in Xcode, and one of my .cpp files instantiates some variables. Another .cpp file in the application uses these variables to instantiate another object and needs them to be instantiated to not throw a null-pointer exception. My solution so far was simply to drag-drop (XCode simplicity) the first file over the second one in the build-phase order. It works fine now, but I have a feeling that it is not the optimal solution, and that there is something fundamentally wrong with my code if I need to organise the compile order manually for the application to run properly.

Should I never instantiate something outside of functions, or what is the golden rule? Thanks.

EDIT: An example as requested. The problem lies in a Observer/Event system. In a source-file I do this:

Trigger* mainMenu_init = new Trigger(std::vector<Event*> {
    // Event(s):
    event_gameInit,

}, [](Event* e) {
    // Action(s):
    std::cout << "Hello World" << std::endl;

});

In the trigger's constructor the Event is asked to add is as an observer:

for(Event* event : events)
        event->addObserver(this);

BUT, the events are just external pointers, so if they are not initialised (which they are in another source-file) this initialisation will fail. So what I found was that if I do not organise the compilation-phase myself, random triggers will not work while other will, depending on if they are built before or after the Event.cpp file.

Was it helpful?

Solution

I assume you are talking about non-trivial initialization of global variables (or of static variables), such as (at the top level of a file):

MyObject *myPtrObject = new MyObject(42, "blah");
MyObject myOtherObject;

("trivial" initialization is, roughly speaking, when there is no constructor involved and everything just involves constants; so if you initialize a pointer to zero, it will be zero before any code is actually invoked)

The order of initialization between different source files is NOT GUARANTEED in C++. It happens to depend on the order of the files with Apple's current system, but THAT MIGHT CHANGE.

So yes, there is something fundamentally wrong.

Golden Rules

  • IMPORTANT: In the initialization of a global object, don't use any other global objects from different source files.
  • Don't overuse global variables. They have numerous disadvantages from a software design point of view.
  • Keep initialization of global objects simple. That will make it easier to stick to the first rule.

Not knowing anything about your program, it's of course hard to give more concrete design advice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top