If I make a size 2 std::vector of a derived class, the constructor is called only once. If I make a size 2 vector of a base class, the constructor is called twice.
I usually wouldn’t post the complete code that duplicates an issue, but in this case it can be made quite short:
#include <iostream>
#include <vector>
class Base {
public:
Base() { std::cout << "base constructor" << std::endl; }
virtual ~Base() {}
};
class Derived : public Base {
public:
Derived() { std::cout << "derived constructor" << std::endl; }
};
int main() {
std::vector<Base> base(2);
std::cout << "----------------" << std::endl;
std::vector<Derived> derived(2);
return 0;
}
The output of the above for me is:
base constructor
----------------
base constructor
derived constructor
Why is the output not the following:
base constructor
base constructor
----------------
derived constructor
derived constructor
I’m using gcc 4.5.2 on Linux.
You’re deceiving yourself: A single default construction of the derived object calls both constructors.
Now, what you are not seeing is the copy constructor, which does in fact get called twice in both cases.
The constructor of
vectorthat you’re calling makes one default construction of its value type, and then copies that into each element: