Issue
Imagine I have a C++ class called MyClass
.
Imagine that I have no access to the source code of MyClass
... it is contained in a library and I am supplied only the library and the header file for MyClass
.
Imagine that the class itself requires environment pre-configuration ... for example ... before the constructor of the class can be called, I need to do some setup. The class is normally meant to be used as follows:
void func() {
doGlobalSetup();
MyClass myInstance(1,2,3);
myInstance.doSomething();
...
}
Now I have the situation where we need to create a global instance of the class such as:
MyClass myInstance(1,2,3);
int main(int argc, char *argv[]) {
doGlobalSetup();
myInstance.doSomething();
}
The problem is that in this story, the instance of MyClass
is created before the call to doGlobalSetup()
. It is instantiated before main()
is called. What I want to do is either defer the creation of myInstance()
till later or be able to run doGlobalSetup()
somehow before the instantiation of the class.
This is a simplification of the actual story ... so let us assume:
- I can't change the internals of
MyClass
. - There must be an instance variable called
myInstance
of typeMyClass
(I can't change the logic toMyClass *pMyInstance
).
Many thanks for reading.
Solution
Within the GCC compiler environment there is a function attribute capability called constructor
. This allows us to flag a function definition with the ability for it to be automatically invoked before main is called and, most importantly before any class constructors are invoked.
Referring back to the original problem definition ... if the doGlobalSetup()
function is modified from:
void doGlobalSetup() { ... }
to
__attribute__((constructor)) void doGlobalSetup() { ... }
then its invocation will occur before main is called and also before any static class instance constructors are called. The explicit call to this function would also be removed from main() as its work has been performed implicitly.
Answered By - Kolban