V
vaysagekv
hi,
how to create an array of objects initializing each object?
thanks in advance
how to create an array of objects initializing each object?
thanks in advance
how to create an array of objects initializing each object?
You can initialize them if you provide a brace-enclosed initialiser list
for the array. You can't do it with a dynamic array, however.
See FAQ 10.5.
Well, if you use a dynamic array everything does get initialised with
the default constructor.
Which may be what the OP wanted. If you want
the elements of the array to be different, you can do this by mesing
about with a static member or a global.
You can initialize them if you provide a brace-enclosed initialiser list
for the array. You can't do it with a dynamic array, however.
*If you have tr1*
#include<array>
#include<iostream>
using namespace std;
struct MyClass
{
MyClass(int i){
cout<< "MyClass(int "<< i<< ")"<< endl;
}
MyClass(const char* s) {
cout<< "MyClass(const char* "<< s<< ")"<< endl;
}
MyClass(int i,int j, int k) {
cout<< "MyClass(this="<< this<< " i="<< i<< " j="<< j<< "
k="<< k<< ")"<< endl;
}
};
void main()
{
array<MyClass,4> arr = { 1, 2, "str", MyClass(1,2,3) };
cout<< "Address of elem at pos 3 is "<< &(arr[3])<< endl;
}
initialization) of the array elements?
I'm not sure what exactly do you mean by "direct initialization".
If it is compile time initialization, then naturally it is not direct
initialization.
If it means, that the object are created in-place, without creation of
temp objects and then copy construction, then it is a direct
initialization. At least with g++ 4.3.2. ( I'm not sure whether
standard requires a temp objects in this case or it allows in-place
object creation)
Leigh is right, g++ requires a public copy constructor, but does not
actually call it
I made a copy constructor with some prints and it had not been called.
Making it private gives a compiler error.
The question is how can optimizer elide function with side effects
(prints)?
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.