Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a construct like Java initializing blocks in C++?

Tags:

java

c++

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

Apart from methods and constructors, Initialization Blocks are the third place in a Java Program where operations can be performed.

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

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

like image 201
Blood-HaZaRd Avatar asked May 09 '12 16:05

Blood-HaZaRd


People also ask

What is Java initialization block?

Initializer block contains the code that is always executed whenever an instance is created. It is used to declare/initialize the common part of various constructors of a class.

What is difference between static block and constructor?

Constructors can't have any return type not even void. Static factory methods can return the same type that implements the method, a subtype, and also primitives. Inside the constructor, we can only perform the initialization of objects.

Is there a static block in C++?

There is no concept with the name "static block" in C/C++. Java has it however, a "static block" is an initializer code block for a class which runs exactly once, before the first instance of a class is created.

What is static initialization block?

Class static initialization blocks are a special feature of a class that enable more flexible initialization of static properties than can be achieved using per-field initialization.


2 Answers

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.

like image 54
Hot Licks Avatar answered Nov 02 '22 05:11

Hot Licks


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).

like image 38
NPE Avatar answered Nov 02 '22 04:11

NPE