Grisu47
Grisu47

Reputation: 552

Order of object construction/initialization

In which order will the ctors be called?

template<class T>
class A {
    public:
        static std::function<void(void)> funcobj;
};

template<class T>
std::function<void(void)> A<T>::funcobj = [](){};

class B : public A<B> {
    public:
        static const int i;

        B::B()
        { 
            DoSomethingHere(); 
        };
}inst;

std::function<void(void)> B::funcobj = [](){};

const int B::i = 2;

Am I right that the order will be something like this?
- const int B::i -> should be hardcoded in a data section of the PE file and thus doesn't need to be constructed at all?
- ctor of std::function for the initialization of A< B >::funcobj
- ctor of A
- ctor of std::function for the initialization of B::funcobj (though A< B >::funcobj and B::funcobj should be technically the same)
- ctor B::B

Upvotes: 0

Views: 104

Answers (1)

radato
radato

Reputation: 930

First the static declarations will be executed in order. So:

template<class T> std::function<void(void)> A<T>::funcobj = [](){};
std::function<void(void)> B::funcobj = [](){};

const int B::i = 2;

(if B::i was an object type instead of an int then its constructor would have been called)

Then when it comes to initializing variable inst, it will start by initializing the parent class i.e. template class A's constructor will be called.

finally class B's constructor will be called.

Upvotes: 1

Related Questions