cavitsinadogru
cavitsinadogru

Reputation: 1030

order of initialization of static types

I was trying to initialize a static member of a class with another class's static member. But I guess because of some 'undefined' reasons, when the initialization happening, initializer was not yet instantiated. So that the data was not copying because of order of instantiation.

Here it is how it looks like,

/* class1.h */
#include "class2.h"

class class1 {
public:
    static const int x;
    static int init()
    {
        return class2::y;
    }
}; 

/* class1.cpp */
const int class::x = class1::init();

/* class2.h */
struct class2 {
    static const int y;
};

/* class2.cpp */
const int class2::y = 5;

It was a rough definition of my purpose. As you can see, I am trying to initialize a static data member of class1 with a function call which returns another class's static data member. As I expect that, instead of class1's data member initialized with the function call, it just 'value-initialized'.

As I guess it is happening because of there is no any specification for the order of static type variable execution.

Is there a way to over it?

Thank you

Upvotes: 1

Views: 98

Answers (1)

Chris Maes
Chris Maes

Reputation: 37742

Besides the question whether this is good design; The answer to your question is rather simple: your definition

const int class2::y = 5;

should occur before

const int class::x = class1::init();

so one way to get it working, is to keep your headers, but put both these lines in your file class1.cpp:

/* class1.cpp */
const int class2::y = 5;
const int class1::x = class1::init();

Upvotes: 1

Related Questions