Зміст курсу
C++ OOP
C++ OOP
Constructor Initialization List
An initialization list is a mechanism used in constructors to provide a way to initialize the data members of a class before the constructor's body is executed. This can be especially useful when dealing with instances that have complex initialization requirements or when working with objects of classes that contain const or reference members.
Syntax of Initialization list
The syntax of initialization lists may appear overly complex and confusing. One might consider using only a constructor as a simpler alternative. However, as the program expands, initialization lists prove to be convenient and straightforward to utilize.
- : (colon): introduces the member initializer list in a constructor.
- member(value): a class member variable being initialized with the value (argument passed to the constructor).
- { } (Braces): the body of the constructor, where additional code can be executed after member initialization.
Limitations and Considerations
There is a common misconception regarding the order of initialization in the initialization list. Contrary to popular belief, initializing variables in the initialization list does not follow the order in which they are written. Instead, it is determined by the member declaration order in the class, not by the sequence in the initialization list.
main
#include <iostream> class Exchanger { public: Exchanger(float _quantity, float _rate) : quantity(_quantity), rate(_rate), total(quantity * rate) {} float quantity, rate, total; }; int main() { Exchanger exchanger(100, 0.3); std::cout << exchanger.total; }
Note
Try to alter the sequence of total variable initialization in the initialization list and in variable declaration within the class.
When you're using initialization lists in a constructor, the argument name can be the same as the attribute name of the class.
main
#include <iostream> class Exchanger { public: Exchanger(float quantity, float rate) : quantity(quantity), rate(rate), total(quantity * rate) {} float quantity, rate, total; }; int main() { Exchanger exchanger(100, 0.3); std::cout << exchanger.total; }
But if you use the same name for both the member variables and the arguments, the total will take the value of the multiplied arguments, not the members. To see this, try setting quantity to zero instead of the argument.
Дякуємо за ваш відгук!