Home > Backend Development > C++ > Can Constructor Arguments and Member Variables Have Identical Names?

Can Constructor Arguments and Member Variables Have Identical Names?

Linda Hamilton
Release: 2024-11-23 07:00:28
Original
409 people have browsed it

Can Constructor Arguments and Member Variables Have Identical Names?

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)
    {}
};
Copy after login

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.
Copy after login

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:

  • Within the constructor, the this pointer can be used to refer to the object being initialized.
  • It is recommended to use const references for constructor arguments to avoid unnecessary copies.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template