C TipsAndTricks
C TipsAndTricks
Contents
1 Avoid Double Initialisation 2 Know what functions C++ silently writes and calls 2 4
Chapter 1
CHAPTER 1. AVOID DOUBLE INITIALISATION Class::Class () : a(0), b(0.0) {} Class::Class (int defaultA, float defaultB) : a(defaultA), b(defaultB) {}
The reason this is better is because initialisation in C++ means that data members of an object are initialised before the body of the constructor is entered. Inside Classs constructor the data members are not being initialised - they are being assigned. Initialisation took place earlier when their default constructors were automatically called prior to entering Class::Class(*). This means that youve allowed the compiler to initialise them to some value without making use of the option available to you to tell the compiler what this initialisation value should be. Initialising variables in the constructor initialisation list means that you can call the default constructor or an overloaded copy-constructor and pass it an initialisation value. This is more ecient than allowing the compiler to call the default constructors and then making extra assignment calls in the constructor body. However, I should stress that because a, b are built in types there is no guarantee that their constructors were called. Again the compiler has the option not to assign default values if this will create extra calls (as mentioned earlier). For other types such as types from the Standard Library (such as std::vector or std::list) initialisation will take place before Classs constructor is entered. There is a gotcha however. Within a class data members are initialised in the order in which they are declared, not in the order you put them in the initialisation list. It is perfectly legal to list them in any order you wish in the constructor initialisation list. It will serve you well, however, to make sure variables declaration order and their order in the initialisation list is the same.
Chapter 2