Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are constructors called?

If I define a local variable instance of a class halfway down my function without using a pointer and new, does the constructor get called on entering the function or where it is defined?

If I define another instance of a class globally within the file does that constructor get called when executable is first loaded? What if multiple threads are accessing the .dll?

Finally is you answer going to be the same in .dll, .so, .exe and linux executables?

like image 469
Tim Matthews Avatar asked Jan 17 '09 00:01

Tim Matthews


2 Answers

If I define a local variable instance of a class halfway down my function without using a pointer and new, does the constructor get called o entering the function or where it is defined?

When it is defined.

If I define another instance of a class globally within the file does that constructor get called when executable is first loaded?

Yes.

What if multiple threads are accessing the .dll?

DLLs usually only get loaded once for the whole application – in fact, DLLs also have an entry point which is called by your application's threads but global variable initialization happens before that and only once.

like image 137
Konrad Rudolph Avatar answered Oct 11 '22 04:10

Konrad Rudolph


If I define a local variable instance of a class halfway down my function without using a pointer and new, does the constructor get called on entering the function or where it is defined?

Such variables have local scope. Their constructor is called when they're defined. For local statics, the constructor is only called once, since the statics will survive multiple function calls and returns. The order is important, and is the order of definition:

void foo() {
    ....
    if(cond) {
        ...
        // called here: first for f, then for b
        static Foo f;
        static Bar b;
    }

    ...
    Foo f; // not static: called here, in every invocation of foo.
}

If I define another instance of a class globally within the file does that constructor get called when executable is first loaded?

Yes, such variable is said to have static storage duration, and namespace scope. Its constructor is called at program start. The order is the order it is defined in the file. That is, a variable defined later will have its ctor called later. The order in which variables defined in different translation units is not defined (look-out for the static initialization order fiasco). But they are all called at program start.

What if multiple threads are accessing the .dll?

All bets are off. The variable is only constructed once. After that, when you start threads and access it, the variable has to be thread safe, or the threads has to do proper locking when accessing the variable.

like image 1
Johannes Schaub - litb Avatar answered Oct 11 '22 05:10

Johannes Schaub - litb