sukumar
sukumar

Reputation: 129

How static object gets initialized at compile time?

class Bird {
public:
   Bird() {
     .....
     .....
    }    
};

void fun() {
    static Bird obj;
}

When compiler compiles the statement static Bird obj It does 2 thing. First is memory allocation for object obj. Second is initialization of obj by calling constructor. My question is if initialization part happens in compile time, how all the statement inside constructor will be executed at compile time

Upvotes: 4

Views: 4813

Answers (4)

lurscher
lurscher

Reputation: 26943

static initialization does not happen at compile time. It happens at run-time, but before main() is invoked.

The order in which static initialization spread across compilation units is not defined. Hence, if you really need static variables, the recommended way is to put all of them on a single static_constructors.cpp, and as a extra benefit, they'll be easier to find

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308138

At compile time, the compiler will set aside a chunk of memory in a special static object area which is part of the program space. That memory will be uninitialized.

Inside the function, the compiler will put an invisible "if" statement which detects that the static object statement is being executed for the first time. If it is the first time, the constructor for the object will be called.

Upvotes: 3

Vinicius Kamakura
Vinicius Kamakura

Reputation: 7778

In that situation, static has a different meaning. It means that obj will be initialized only once, at the first time fun() is called and obj will remaing valid between calls to fun().

Think of it as a global variable, but only the function fun() can see it :P

Upvotes: 0

iammilind
iammilind

Reputation: 69988

When compiler compiles the statement static Bird obj It does 2 thing. First is memory allocation for object obj. Second is initialization of obj by calling constructor.

No. The memory is already allocated at compile time (before the program gets executed). It's just that initialization happens when the execution touches the static Bird obj; statement. This is called lazy initialization.

Also, note that, in case if Bird() constructor throws an exception, then the initialization will not be finished. So again when the fun() is called, obj is again tries to get initialized. It happens until the obj initializes successfully. After that, that line will not be executed any more.

Upvotes: 2

Related Questions