Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top