32

Consider the below program:

class A
{
    public:
    A(int i)
    {
            cout<<"Called"<<endl;
    }
};

int main()
{
    vector<A> v(5,A(1));
    return 0;
}       

I am getting the output: http://ideone.com/81XO6

 Called

Why the constructor gets called only once even if we are constructing 5 objects?
How vector is internally handled by the compiler?

5
  • 7
    The others are initialized by the copy constructor.
    – jxh
    Commented Jul 22, 2012 at 6:31
  • 7
    ideone.com/lHX5W Commented Jul 22, 2012 at 6:32
  • 1
    @Benjamin Lindley: you should write that in an answer
    – nico
    Commented Jul 22, 2012 at 6:33
  • Why one extra copy is done? I mean one object is already constructed,right. Commented Jul 22, 2012 at 6:33
  • @Aashish: The first constructor is for a temporary object. The one you construct with A(1). That temporary is copied into the vector five times. It cannot be constructed directly in the vector as you have it. (Well, I guess it could, if your compiler was smart enough. But it's not.) @Pooya: What are you talking about? That is definitely not the case. Commented Jul 22, 2012 at 6:37

2 Answers 2

40

Your class has two constructors and you are watching only one of them. std::vector creates its elements by copy-constructing them from the original element you supplied. For that purpose, the copy-constructor of class A is called 5 times in your example.

The copy-constructor for A in your example is implicitly declared and defined by the compiler. If you so desire, you can declare and define it yourself. If you print something from it, you will see that it is called at least 5 times.

3
  • Assuming no resizing, would it be 5 times or just 4 times? Is the original copy used?
    – Mysticial
    Commented Jul 22, 2012 at 6:39
  • 3
    @Mysticial: I don't expect any compiler to be able to use the original directly. How? The elements are stored in a dynamic memory block, which is allocated after the original element is constructed. So, all 5 elements have to be copied from the original. Commented Jul 22, 2012 at 6:41
  • Now that I think about it, you're right since it's in the wrong scope.
    – Mysticial
    Commented Jul 22, 2012 at 6:42
12

It gets called once since the line

vector<A> v(5,A(1)); 

will call the constructor and the line becomes vector v(5,X);

where X is the object constructed after calling the constructor.

After that the copy constructor is used.

Try adding

A(const &A);

To the class declaration to verify this.

Not the answer you're looking for? Browse other questions tagged or ask your own question.