Home >Backend Development >C++ >Are Constructor Argument and Member Variable Names Allowed to Overlap in C ?

Are Constructor Argument and Member Variable Names Allowed to Overlap in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-12 21:49:01562browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn