0

I've got an abstract superclass, KFilter with a static map member, static map<KFILTER_TYPE, FilterFactory*> factories;. As you can see, I use factories and this map has the respective ones for each subclass by a custom Enum, KFILTER_TYPE. Now, I initialize the factories map in the cpp file of the superclass:

//KFilter.cpp

<KFILTER_TYPE, FilterFactory*> KFilter::factories = <KFILTER_TYPE, FilterFactory*>();

To automatically bind the factories, I have a macro, #define REGISTER_TYPE(filterName, filterENUM), which I use at the top of each subclass, like REGISTER_TYPE(EKFilter, EKF). This uses a line which registers the factory of the subclass to the map of the superclass.

However, I get a runtime error, with Exception thrown: read access violation.. After durdling around, I've figured this is because the macro executed in the subclass gets called before the static map is initialized in the cpp of the superclass. My question is, why does this happen? I thought that the superclass, with its .h and .cpp would compile before the subclasses. Heck, I didn't even include the subclasses in either my main or the superclass header. What gives and how could I fix it?

Thanks in advance!

SparksH
  • 1
  • 3
  • Are these factories and registerers stored as global variables? –  Jul 12 '17 at 13:36
  • 2
    static initialization order fiasco – NathanOliver Jul 12 '17 at 13:36
  • 1
    Possible duplicate of [C++ static initialization order](https://stackoverflow.com/questions/1005685/c-static-initialization-order) –  Jul 12 '17 at 13:37
  • @Frank The factor classes are made my a macro that's called in each subclass, they map is a static member of the superclass, not a global variable. – SparksH Jul 12 '17 at 13:39
  • 1
    @SparksH static member variables are global. The name is scoped to the class but it suffers the same thing as regular global variables. – NathanOliver Jul 12 '17 at 13:40
  • @Frank I've tried wrapping the initialization in a function, but where do I call that one? I can't call it outside the class definition. – SparksH Jul 12 '17 at 13:42

0 Answers0