Home > Backend Development > C++ > Constructor Initialization with Same Name: C Standard Compliance?

Constructor Initialization with Same Name: C Standard Compliance?

Patricia Arquette
Release: 2024-11-15 10:18:03
Original
405 people have browsed it

Constructor Initialization with Same Name: C   Standard Compliance?

Constructor Initialization of Member Variables Using Same Names: C Standard Compliance?

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

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

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!

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