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

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

Susan Sarandon
Release: 2024-12-12 10:53:09
Original
770 people have browsed it

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

Member Variable Initialization with Same-Named Constructor Arguments

In C , it is possible to initialize member variables using constructor arguments with the same names as the member variables. This technique, as demonstrated in the example below, has been confirmed to work without warnings or errors when compiled with g 4.4 and clang .

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

According to the C standard (§12.6.2/7), this initialization is legal and guaranteed to work. The names in the expression-list of a mem-initializer are evaluated in the scope of the constructor, allowing the this pointer to be used to refer to the object being initialized.

In the example above, the constructor argument vec is initialized to the member variable vec with the same name. This initialization occurs each time an object of class Blah is created.

Recommendation

Consider accepting the constructor parameter as a const reference to avoid unnecessary copying of the original vector object, as seen below:

Blah(const std::vector<int> &amp; vec): vec(vec) {}
Copy after login

The above is the detailed content of Can C Member Variables Be Initialized Using Constructor Arguments with the Same Name?. 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