Home >Backend Development >C++ >Can Member Variables Be Initialized with Constructor Arguments of the Same Name in C ?
Using Constructor Arguments with the Same Name as Member Variables
Original Question:
Is it permissible under the C standard to initialize member variables using the same name as constructor arguments?
Response:
Yes, the C standard permits this approach. The code initializes member variables according to the names provided in the constructor arguments. The following example illustrates this:
#include <cstdio> #include <vector> class Blah { std::vector<int> vec; public: Blah(std::vector<int> vec) : vec(vec) {} void printVec() { for (unsigned int i = 0; i < vec.size(); i++) printf("%i ", vec.at(i)); printf("\n"); } };
Standard Reference:
The C standard (§12.6.2/7) states that "Names in the expression-list of a mem-initializer are evaluated in the scope of the constructor for which the mem-initializer is specified."
Additional Considerations:
The example also demonstrates that using const std::vector
The above is the detailed content of Can Member Variables Be Initialized with Constructor Arguments of the Same Name in C ?. For more information, please follow other related articles on the PHP Chinese website!