Please consider the following example
struct Foo
{
int bar;
Foo(int i):bar(i){cout << "real ctor\n";}
Foo(){cout << "default ctor\n";}
};
int main()
{
Foo fooArr[3];//default ctor called 3 times
for(int i=0;i!=3;++i)cout << fooArr[i].bar << endl;//bare memory junk
cout << endl;
vector<Foo> fooVec;
for(int i=0;i!=3;++i){
fooVec.push_back(Foo(i)); //only real ctor called
cout << fooVec[i].bar << endl;//real thing
}
cout << endl;
int iArr[3];
for(int i=0;i!=3;++i)cout << iArr[i] << endl;//bare memory junk
}
I don’t want any user of Foo to call its default constructor, because it’s not in my design. But I’d like my users to be able to use an array of Foo, to support that, I was forced to provide a pointless and confusing Foo::Foo(). I just don’t understand why does the C++ standard force programmers to do such a thing. What is the rationale behind it? Why the inconsistency? Could any of you smart guys who get this explain it to me, please? Thanks in advance!
You can make arrays of
Fooeven if it doesn’t have a default constructor. It’s just that the elements have to be constructed when you declare the array. So you can do this:The alternative is to use a a dynamic array (your
vector<Foo>example, which is probably best) or an array of pointers toFoo(likeshared_ptr<Foo> arrFoo[3])A final note about
vector<Foo>: since the size of the array is known in advance, you can improve performance by reserving enough space in the vector for all futureFoos:EDIT: Your question was why do you have to have a default constructor to make a static array of the type. I thought the answer was clear but I’ll try to explain it.
Foo bar1; Foo bar2;creates two objects using the default constructor, since no arguments were provided.Foo bar[2];is essentially the same thing. It declares two objects that need to be constructed. There is no way to declare an object without constructing it – that’s the very point of declaring it in the first place.A static array in C++ is just a bunch of objects placed contiguously memory. It’s not a separate object.
Hope that makes sense.