Reputation: 4747
Is it possible to instantiate an object of a class even before main() executes? If yes, how do I do so?
Upvotes: 4
Views: 1180
Reputation: 92854
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";
}
Upvotes: 7
Reputation: 25140
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";
}
Upvotes: 5