0

If the program execution in c++ starts in main function, when will the programming class's object be generated during execution?

#include<iostream>

using namespace std;

class programming
{
   private:
      int variable;

   public:

      void input_value()
      {
         cout << "In function input_value, Enter an integer\n";
         cin >> variable;
      }

      void output_value()
      {
         cout << "Variable entered is ";
         cout << variable << "\n";
      }
};

programming object;

main()
{

   object.input_value();
   object.output_value();

   return 0;
}

can anybody help?

4

4 回答 4

6

Since object is a static (i.e. global) variable, its constructor is executed when the global constructors are run, i.e. before main() starts executing.

于 2013-06-04T16:03:02.657 回答
3

It is created before main starts. In C++, some "program execution" can occur before main.

于 2013-06-04T16:02:37.610 回答
1

YOUR program starts with your code in main, but "things" happen before that. Some compilers/environments will add some extra code just at the beginning of main to create global objects, in other cases, the creation of global is code that runs just before main. All you need to really care about is that "it happens before any of your code".

However, you can't rely on global objects being initialized before some OTHER global objects....

于 2013-06-04T16:03:38.563 回答
1

In C++, global objects are created as static data before main is called. This means that memory is allocated on neither the stack nor the heap, but instead is placed in memory in a data segment. A data segment is an area of memory laid out in a manner similar to how a program's execution code is stored. The memory is allocated when the program is loaded into memory before any code runs.

C++ does not require that global objects be created in any particular order. The only guarantee is that they will be created before main is called. That is, assume global constructors are called essentially at random.

于 2013-06-04T16:06:32.093 回答