I have a class like this:
struct event_counts { uint64_t counts[MAX_COUNTERS]; event_counts() : counts{} {} // more stuff };
Usually I want to default (zero) initialize the counts
array as shown.
At selected locations identified by profiling, however, I'd like to suppress the array initialization, because I know the array is about to be overwritten, but the compiler isn't smart enough to figure it out.
What's an idiomatic and efficient way to create such a "secondary" zero-arg constructor?
Currently, I'm using a tag class uninit_tag
which is passed as a dummy argument, like so:
struct uninit_tag{}; struct event_counts { uint64_t counts[MAX_COUNTERS]; event_counts() : counts{} {} event_counts(uninit_tag) {} // more stuff };
Then I call the no-init constructor like event_counts c(uninit_tag{});
when I want to suppress construction.
I'm open to solutions that don't involve the creation of a dummy class, or are more efficient in some way, etc.
Example 2: Java private no-arg constructor Here, the constructor does not accept any parameters. Hence, it is known as a no-arg constructor. Notice that we have declared the constructor as private. Once a constructor is declared private , it cannot be accessed from outside the class.
Answer to your question is No. Java won't provide a default constructor if you write any kind of constructor in class. One difference between them is that the body of default constructor will always be empty whereas we can insert our own code in no-arg constructor.
In Java, a no-argument constructor is the default constructor and if you don't define explicitly in your program. Then Java Compiler will create a default constructor with no arguments. The purpose is to call the superclass constructor.
The technique of having two (or more) constructors in a class is known as constructor overloading. A class can have multiple constructors that differ in the number and/or type of their parameters. It's not, however, possible to have two constructors with the exact same parameters.
The solution you already have is correct, and is exactly what I'd want to see if I were reviewing your code. It is as efficient as possible, clear and concise.
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