Initialize a class object before main ()

Is it possible to instantiate a class object before main () is executed? If so, how to do it?

+6
c ++
source share
2 answers

Global objects are created before calling main() .

 struct ABC { ABC () { std::cout << "In the constructor\n"; } }; ABC s; // calls the constructor int main() { std::cout << "I am in main now\n"; } 
+7
source share

Yes, you can do it like this:

 #include <iostream> struct X { X() { std::cout << "X()\n"; } }; X x; int main( int argc, char ** argv ) { std::cout << "main()\n"; } 
+5
source share

All Articles