Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is constructor called for a static object

Tags:

c++

I understand that static variables are initialized at compile time, but what about a static object?

e.g. if I have the following code:

class A {
    A();
};

A::A(){
    std::cout << "Constructing A" << std::endl;
}

int main(){
    std::cout << "Hello World!" << std::endl;
    static A A_obj;
    std::cout << "Goodbye cruel world" << std::endl;
    return 0;
}

Should I expect the output to be:

Hello World!
Constructing A
Goodbye cruel world

or

Constructing A
Hello World!
Goodbye cruel world
like image 254
Melandru's Square Avatar asked Dec 10 '22 08:12

Melandru's Square


1 Answers

"I understand that static variables are initialized at compile time"

Not true. static variables at function scope are strictly initialised at the point of first encounter. And will be destructed after the closing brace of main.

You'll get output in this order:

Hello World!
Constructing A
Goodbye cruel world
like image 167
Bathsheba Avatar answered Jan 05 '23 07:01

Bathsheba