Home > Backend Development > C++ > body text

Can Member Variables Be Initialized with Constructor Arguments of the Same Name in C ?

Susan Sarandon
Release: 2024-11-13 03:35:02
Original
885 people have browsed it

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

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 &vec as the parameter type can avoid unnecessary copying of the original vector object.

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!

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