Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Constructors: Using an initializer vs setting the values in the definition

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:

  1. Of the two methods of setting the variables, which is better for performance?
  2. Is one method generally preferred for general coding standards in C++?
  3. Can you mix both methods?
like image 860
kingcobra1986 Avatar asked Sep 03 '25 05:09

kingcobra1986


2 Answers

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 PODs like ints, 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.

like image 56
Sam Varshavchik Avatar answered Sep 04 '25 20:09

Sam Varshavchik


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.

like image 22
Taztingo Avatar answered Sep 04 '25 18:09

Taztingo