Home >Backend Development >C++ >Are Constructor Argument and Member Variable Names Allowed to Overlap in C ?
Initializer Lists in Constructors: Overlapping Names with Member Variables
The practice of initializing member variables using the same names as constructor arguments has raised questions about its validity and compliance with C standards. Let's explore the standard's perspective on this practice.
According to the C standard, §12.6.2/7, the expressions in a member initializer's expression list are evaluated within the scope of the constructor. Therefore, using the same name for both a constructor argument and a member variable is explicitly allowed.
For example, the following code snippet is fully compliant with the C standard:
class Blah { std::vector<int> vec; public: Blah(std::vector<int> vec): vec(vec) {} // ... };
In this case, the constructor argument vec is used to initialize the member variable vec without any ambiguity.
Furthermore, the standard allows the use of the this pointer in member initializers to refer to the object being initialized. This enables the initialization of member variables based on other member variables, as shown in the following example:
class X { int a; int b; int i; int j; public: X(int i): r(a), b(i), i(i), j(this->i) {} // ... };
However, it's worth noting that passing the constructor parameter as a const reference can enhance the code's efficiency by avoiding unnecessary copying of the original vector object. This can be achieved by modifying the constructor as follows:
Blah(const std::vector<int> &vec): vec(vec) {}
The above is the detailed content of Are Constructor Argument and Member Variable Names Allowed to Overlap in C ?. For more information, please follow other related articles on the PHP Chinese website!