Take the 2-minute tour ×

I read in some articles that there is something called Initializing blocks in java ; where we can perform some initializing assignements When the Class is loaded or an instance is created.


class InitDemo
     static int y;
     int x;
   y = 10;
   x =  0;

I am asking if there is such paradigme in C++ ? Thank you.

share|improve this question
C doesn't have the concept of classes being "loaded", and its view of statics is entirely different from Java's. So, aside from static initializers there's nothing similar. –  Hot Licks May 9 '12 at 16:37
(In essence, the static block in Java is the class's constructor, because classes are (semi-)full-fledged objects. C++ classes are not objects.) –  Hot Licks May 9 '12 at 16:39
Thank you for the informations, that was helpfull. –  Blood-HaZaRd May 9 '12 at 16:53
(I should point out that your block above is not a static init block. See my post below.) –  Hot Licks May 9 '12 at 18:21
add comment

2 Answers

up vote 4 down vote accepted

It needs to be pointed out that there are two different forms of initialization blocks in Java. The bare {...} block, without the keyword static, is just a bit of compiler swizzling -- the text in the block is appended to the front of any constructors that are defined -- no separate code segment is generated. A block that begins static {..., on the other hand, is a static initialization block and a (semi-)proper procedure in its own right (named, not surprisingly, "static").

The static block is executed only once, immediately (with a few caveats) after the class is loaded. The non-static initializer is (by virtue of being copied into the constructors) executed every time a constructor is executed, and hence is generally inappropriate for static init.

share|improve this answer
add comment

In a nutshell, C++ does not have a direct equivalent for this Java construct.

To get similar behaviour, you would have to set x and y from InitDemo's constructors (which you can also do in Java).

share|improve this answer
Yes indeed aix, i see that in contrast of java the constructors remain the only* place fo initilizing assignements for C++. –  Blood-HaZaRd May 9 '12 at 16:43
@Blood-HaZaRd: Pretty much. In Java, a (non-static) initialization block is just a way to place some common code into every constructor. –  NPE May 9 '12 at 16:44
Yes and beside that there is two flavors static intilizing blocks and non-static which i think is helpfull. –  Blood-HaZaRd May 9 '12 at 16:46
add comment

Your Answer


