Home >Backend Development >C++ >Can Member Variables Be Initialized with Constructor Arguments of the Same Name in C ?

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

Susan Sarandon
Susan SarandonOriginal
2024-11-13 03:35:02931browse

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

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!

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