The first way, by doing : exampleChar(c), exampleInt(i) , is called a list of initializers.
If you do this in the second way, two variables are built by default by default 1 then you assign them a value. (When the actual constructor element is introduced, everything that was not initialized by the initializer list is built by default.) This is a waste of time because you are simply rewriting the values anyway. For small types, such as int or char , this does not really matter, but when these member variables are large types that require many loops to build, you definitely want to use a list of initializers.
The second method will not lose time by indicating to it the default value and then overwriting it - it will set its values directly to the value that you give it (or call the right constructor if the element is an object).
You can understand what we mean:
class MyClass { public: int _i; // our data // default constructor MyClass() : _i(0) { cout << "default constructor"; } // constructor that takes an int MyClass(int i) : _i(i) { cout << "int constructor"; } // assignment operator void operator=(int i) { _i = i; cout << "assignment operator"; } }; class OtherClass { public: MyClass c; OtherClass() { c = 54; } }; OtherClass oc;
You will see that
default constructor assignment operator
. These are two function calls that can be expensive for other classes.
If you change the constructor of OtherClass to
OtherClass() : c(54) { }
You will see that
int constructor
. Just one call compared to two. This is the most effective way.
Initializer lists are also required when you
have types that do not have a default constructor. You must call the correct constructor in the initializer list.
has a const member that you want to give some value (instead of just having a default value by default
have a reference element. You should use initialization lists on them.
tl; dr: do it because it is at least as fast, but not slower than the other, and sometimes much faster.
1 For built-in types such as int and char , they are not actually constructed; they simply have the value of any memory they used to be with.