сряда, 8 октомври 2008 г.

Java like static blocks in C++

Hi there. I recently moved from java to c++ and I needed a java like static block, but realized that there is no "static { ... }" in c++ so this post is about static blocks in c++, why we need them and how do we write java like static blocks is c++.

Let me have a class like this:


class demo_class {

private: static vector<int> statv;

public: demo_class(int i) {

printf("%d\n", statv[i]);

}

};

/* if you miss this line here, the linker will cry that it can't find a definition for this demo_class::stdev */


vector<int> demo_class::statv = vector<int>(); // line x


And I want this statv vector to be filled with some values before we create an object of this demo_class. The trick here is to define a global static variable of some type and to use its default constructor as a static block. The exercise is even more difficult if the static members are private. But the c++ language has tools for that too. What I need to do is to define this help type, in this case it will be a structure, in demo_class and mark it as "friend" in order to have access of the private static members. Add this `friend struct static_block;` after the constructor. Now I have declared a friend type of our class. I still don't have a definition of this type and I'll do it outside the class definition in а .cpp file just before i create an object from this type static_block. The code goes like this:


static struct static_block {

static_block() {

printf("static_block()\n");

/* you can miss this line here only if you declare _STATIC_BLOCK_INSTANCE after line x. That way you are shure that demo_class::statv will be created and you can use it.*/

demo_class::statv = vector<int>();

for (int i = 0; i <>

demo_class::statv.push_back(i * i);

}

} _STATIC_BLOCK_INSTANCE;


So this is it. The code should work. But remember don't try to use c++ as java ... you will not go any further.

1 коментар:

Dilyan каза...

Hi, Vesko
In addition to the post for your C# readers i may say that in C# the equivalent of the static blocks is Static Constructors. :)