简体   繁体   中英

How object can be created outside main function?

I don't understand the output of this code:

  • How the object a1 of class A is created and constructor is called?
  • Why the object a1 is created outside the main function?
#include<iostream>
using namespace std;     
class A
{
    public:
    A(int i)
    {
        std::cout<<"I am in A Class "<< i <<endl;
    }
};
 A a1(8);

int main()
{
    A a(9);
    return 0;
}

Output:

I am in A class 8
I am in A class 9

whats the reason that object can create first outside main function

In your example a1 has global namespace scope and has static storage duration .
It is constructed at program startup and therefore you see

I am in A class 8

printed out before

I am in A class 9

a1 is a global variable. Globals are constructed before main is invoked.

It's technically implementation dependent.

Except that a1 has to be constructed before it gets used.

In your example, main() isn't using a1. However, a simple way for a C++ implementation to make sure that a1 is constructed before it gets used is to just have a1 (and any non-local non-inline variables with static storage) be constructed/initialized before main().

Reference: "It is implementation-defined whether the dynamic initialization of a non-local non-inline variable with static storage duration is sequenced before the first statement of main or is deferred. If it is deferred, it strongly happens before any non-initialization odr-use of any non-inline function or non-inline variable defined in the same translation unit as the variable to be initialized"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM