Question

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

Was it helpful?

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.)

OTHER TIPS

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 done to be more explicit. For non POD types this is not necessary as the default constructor is automatically called for them. If the types default constructor has not been defined or is not accessible, this will cause a compile error.

This makes the most sense for POD types, as their value is undefined when they are not initialized.

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

struct A
{
    int  t;
    A() : t() { /* value of t is t's default value of 0 */ }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top