Using Identical Constructor Argument and Member Variable Names
Question:
Is it permissible to initialize member variables using the same names as constructor arguments, as illustrated in the following code?
class Blah { std::vector<int> vec; public: Blah(std::vector<int> vec): vec(vec) {} };
Answer:
Yes, this practice is fully compliant with the C standard. According to section 12.6.2/7 of the standard:
Names in the expression-list of a mem-initializer are evaluated in the scope of the constructor for which the mem-initializer is specified.
This implies that within the constructor initialization list, the member variables can be referenced using the same names as the constructor arguments. Thus, the code you provided is both legal and guaranteed to work correctly.
Additional Information:
The above is the detailed content of Can Constructor Arguments and Member Variables Have Identical Names?. For more information, please follow other related articles on the PHP Chinese website!