So reading through one of my text books, I came across the initializer for constructors. I would like to know if there is any performance differences and which is the preferred method for general coding standards for C++.
Assume:
Example:
//Setting each private variable with assignment statements
SampleClass::SampleClass()
{
a = 0;
b = 0;
}
//Using initializers to set the private variables
SampleClass::SampleClass() : a(0), b(0)
{
}
I would imagine if there is a constructor that has parameters and the parameters need some sort of validations, it's best to use the methods that validate within. That being said, would you mix them?
Example:
SampleClass2::SampleClass2(int fNumber, int sNumber) : a(fNumber)
{
makeSureNotZero(sNumber);
}
Just to clarify the questions:
There is no law against mixing both methods.
In the case of PODs, there is not going to be any measurable difference between either method, and the C++ compiler is likely to generate identical code for both methods of initialization.
On the other hand, if the class members are more complex classes, rather than POD
s like int
s, constructor initialization will produce better results. This is only a rule of thumb, and the actual results will vary, depending on each particular class. It is not entirely implausible that default-constructing an instance of a class, and then invoking its assignment operator, will give better results than directly constructing it.
My answer is it depends on the compiler. Most compilers should be smart enough to optimize both of those, and make them equivalent. If the compiler wasn't a factor then just by looking, and thinking about it I would assume the initializer list. It initializes the member variable with it, instead of having to initialize it and then set it. It might be just a few instructions less, but I would let the compiler handle it.
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