Search code examples
c++initializationmember-variables

Put a parenthesis after member variable to initialize?


I have seen people put a parenthesis after the member variable in the initialization list. I wonder why would people do that?

For example, I have a STL container in header file:

class A{
public: 
    A();
    ...
private: 
    vector<string> v;
}

and in source file:

A::A() : v() {}

My question is what is v() and why do people do that since that doesn't look like v is initialized into a value either


Solution

  • That will run the default constructor or initializer (for plain types) for the member. In this context, it will default construct the vector. Since it is the default constructor, it is not necessary here. v would have been default constructed in the absence of an initializer.


    class Example {
    
    private:
        int defaultInt;
        vector<int> defaultVector;
        int valuedInt;
        vector<int> sizedVector;
    
    public:
    
        Example(int value = 0, size_t vectorLen = 10) 
            : defaultInt(), defaultVector(), valuedInt(value), sizedVector(vectorLen)
        {
            //defaultInt is now 0 (since integral types are default-initialized to 0)
            //defaultVector is now a std::vector<int>() (a default constructed vector)
            //valuedInt is now value since it was initialized to value
            //sizedVector is now a vector of 'size' default-intialized ints (so 'size' 0's)
        }
    
    };
    

    For kicks and giggles, you could also do thirdVector(vectorLen, value) to get a vector with vectorLen elements with the value value. (So Example(5, 10) would make thirdVector a vector of 10 elements valued 5.)