Reputation: 1
I don't understand the output of this code:
a1
of class A
is created and constructor is called?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
Upvotes: 0
Views: 793
Reputation: 10998
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
Upvotes: 1
Reputation: 73
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"
Upvotes: 1
Reputation: 2450
a1
is a global variable. Globals are constructed before main
is invoked.
Upvotes: 0