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:
- That the default constructor doesn't take any parameters (so no validtion needed)
- The class has two private variables: int a and int b
- Both variables need to be set to 0
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:
- Of the two methods of setting the variables, which is better for performance?
- Is one method generally preferred for general coding standards in C++?
- Can you mix both methods?