Place the parenthesis after initializing a member variable?

I've seen people put parentheses after a member variable in the initialization list. I wonder why people did this?

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

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

      

and in the source file:

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

      

My question is what is v () and why people are doing it as it doesn't seem like v is value-initialized

+3


source to share


2 answers


This will trigger the default constructor or initializer (for simple types) for the member. In this context, it will construct the vector by default. Since it is the default constructor, it is not needed here. v

would be built by default 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 bumps and giggles, you can also do thirdVector(vectorLen, value)

to get vector

with elements vectorLen

with meaning value

. (So Example(5, 10)

do thirdVector

vector 10

elements assessed 5

.)

+5


source


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

This is sometimes made more explicit. For types without PODs, this is optional, as the default constructor is automatically called for them. If a default constructor for types is not defined or is not available, this will result in a compilation error.



This is most convenient for POD types as they are undefined when not initialized.

struct A
{
    int  t;
    A() : { /* value of t undefined */ }
}

struct A
{
    int  t;
    A() : t() { /* value of t is t default value of 0 */ }
}

      

+2


source







All Articles