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:
MyClass
.myInstance
of type MyClass
(I can't change the logic to MyClass *pMyInstance
).Many thanks for reading.
Since you've constrained the problem such that new
cannot be used, you should be able to create the object as always and copy it to the global instance. For example:
MyClass createMyClass()
{
doGlobalSetup();
return MyClass(1, 2, 3);
}
MyClass myInstance = createMyClass();
int main()
{
myInstance.doSomething();
return 0;
}
Does it suit your needs?
namespace
{
int doStaticGlobalSetup()
{
doGlobalSetup();
return 0;
}
}
MyClass myInstance(doStaticGlobalSetup() + 1,2,3);
int main() {
myInstance.doSomething();
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With