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.
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.
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With