I know that in C++ the declaration of members in the class header defines the initialization order. Can you tell me why C++ choose this design? Are there any benefits to force the initialize order instead of following the initializer list?
Initializing a variable as Telastyn pointed out can prevent bugs. If the variable is a reference type, initializing it can prevent null reference errors down the line. A variable of any type that has a non null default will take up some memory to store the default value.
Without initialization, a variable would have an unknown value, which can lead to unpredictable outputs when used in computations or other operations.
The main reason is that initialization applies to an object, or an instance, and in the declaration in the class there is no object or instance; you don't have that until you start constructing. There's been some evolution in this regard.
In C programming language, the variables should be declared before a value is assigned to it. In an array, if fewer elements are used than the specified size of the array, then the remaining elements will be set by default to 0.
Declaration tells the compiler about the existence of an entity in the program and its location. When you declare a variable, you should also initialize it. Initialization is the process of assigning a value to the Variable. Every programming language has its own method of initializing the variable.
That means, just as C.47 says: Define and initialize member variables in the order of member declaration . If I rearrange the member variable declarations, I can change the values that end up in those member variables when the initializer runs.
This code harbors a bug that’s as subtly harmful as it is hard to spot hence Write member initializers in the same order as their declaration Many compilers (but not all) will issue a warning if you break this rule. Modern compilers Clang, MSVC detect it with the right use of right warning flags.
Initialize Member Variables in the Order You Declare Them. Even so, you'll often see one variable initialized from another, for example FullName being initialized from FirstName and LastName, or a pointer variable being initialized with a call to new, and another variable initialized with a call to some function of that newly created object.
Constructors could be overloaded while destructor can't. If data members could be initialized in different order for different constructors, then the destructor can't guarantee to perform destruction on data members in the reverse order of their construction (for objects constructed by different constructors).
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