Shree
Shree

Reputation: 4747

Instantiate object of a class before main() executes

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

Answers (2)

Prasoon Saurav
Prasoon Saurav

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

Edric
Edric

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

Related Questions