Question:
Is it within the C standard to initialize member variables using a constructor argument that shares the same name as the member variable?
Example:
class Blah { std::vector<int> vec; public: Blah(std::vector<int> vec): vec(vec) {} };
Answer:
Yes, it is legal and guaranteed to work according to the C standard.
Explanation:
Section 12.6.2/7 of the C standard states, "Names in the expression-list of a mem-initializer are evaluated in the scope of the constructor for which the mem-initializer is specified." In other words, the constructor argument and the member variable are distinct entities, but they use the same name.
This allows us to initialize the member variable with the value of the constructor argument, as shown in the example.
Note:
It is recommended to use const references for constructor arguments to avoid unnecessary copying of objects. So, it would be more preferable to use:
Blah(const std::vector<int> &vec): vec(vec) {}
The above is the detailed content of Constructor Initialization with Same Name: C Standard Compliance?. For more information, please follow other related articles on the PHP Chinese website!