views:

388

answers:

2

While reading the answers to this question I got a doubt regarding the default construction of the objects in the vector. To test it I wrote the following test code:

struct Test
{
    int m_n;

    Test(); 

    Test(const Test& t);

    Test& operator=(const Test& t);
};

Test::Test() : m_n(0)
{
}

Test::Test(const Test& t)
{
    m_n = t.m_n;
}

Test& Test::operator =(const Test& t)
{
    m_n = t.m_n;
    return *this;
}


int main(int argc,char *argv[])
{
    std::vector<Test> a(10);
    for(int i = 0; i < a.size(); ++i)
    {
     cout<<a[i].m_n<<"\n";
    }

    return 0;
}

And sure enough, the Test structs default constructor is called while creating the vector object. But what I am not able to understand is how does the STL initialize the objects I create a vector of basic datatype such as vector of ints since there is default constructor for it? i.e. how does all the ints in the vector have value 0? shouldn't it be garbage?

+9  A: 

It uses the equivalent of the default constructor for ints, which is to zero initialise them. You can do it explicitly:

int n = int();

will set n to zero.

Note that default construction is only used and required if the vector is given an initial size. If you said:

vector <X> v;

there is no requirement that X have a default constructor.

anon
We seem to have a lot of time at hands, today :)
xtofl
That's the joy of the recession :-(
anon
I didnt know that.. Well what do we call int() as? Then again why dont we have default initializers for Basic Data types.
Canopus
We don't have default initialisation for basic types because it costs something, and the C++ mantra is that you must not be forced to pay a price for something you may not need.
anon
+1  A: 
std::vector<Type> a(10);        // T could be userdefined or basic data type

Vector basically calls default for the type to which it points: Type()

  • if it is basic data type like int, double are there then int(), double() { int() will get value 0}
  • if the user defined data type then default constructor would be called.
aJ