Is it possible to instantiate an object of a class even before main() executes? If yes, how do I do so?
+13
A:
Global objects are created before main() gets called.
struct ABC {
ABC () {
std::cout << "In the constructor\n";
}
};
ABC s; // calls the constructor
int main()
{
std::cout << "I am in main now\n";
}
Prasoon Saurav
2010-10-22 10:12:12
How does this work? Doesn't the execution start at main()? Can you throw some light?
Shree
2010-10-22 10:17:23
@Shree : Check out the edits. Working code [here](http://ideone.com/mKEB9)
Prasoon Saurav
2010-10-22 10:18:29
@Shree: No. Global (and a few other) variables have to be created before `main()`, because they are required to be usable when `main()` starts. So their constructors have to be called before `main()`.
sbi
2010-10-22 10:21:55
Is this guaranteed: "It is implementation-defined whether the dynamic initialization of a non-local variable with static storage duration is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first use of any function or variable defined in the same translation unit as the variable to be initialized. Also refer 3.6.2/3 which to me looks like can also take over and 's' constructor may not even be called
Chubsdad
2010-10-22 10:55:20
@Chubsdad: you're right for globals defined in a different TU than `main` itself - their initialization might be deferred. But in Prasoon's example, of course `s` must be initialized "before the first use of any function or variable defined in the same translation unit", and hence before `main` is entered.
Steve Jessop
2010-10-22 12:53:46
+5
A:
Yes, you can do it like so:
#include <iostream>
struct X {
X() { std::cout << "X()\n"; }
};
X x;
int main( int argc, char ** argv ) {
std::cout << "main()\n";
}
Edric
2010-10-22 10:16:51