https://stackoverflow.com/a/8839647/462608
Use the static initializer:
public class MyClass { static { //init } }
Can something similar be done in C++?
Actually, I need to initialize some variables, but I don’t want to create an object.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If the variables are
staticmembers, not only are you able to initialize them, but you must initialize them.There’s no direct equivalent of Java initializer lists, but something similar can be done calling a function to initialize a static member:
This is for cases with intense logic. If all you want is to initialize
staticmembers, just do it similar toX::x.If the variables are outside the class, initialize them directly (don’t need calling code for that).
If the variables are
staticmembers of the class, use one of the above approaches.If the variables are non-
staticmembers, they simply don’t exist without an object.