I know in c++11 I can use initializer to create array/vector elements one by one like:
int ar[10]={1,2,3,4,5,6};
vector<int> vi = {1,2,3,4};
This is done manually, but what if I wish to initialize an array/vector with 10000 elements and specify their value, can it be done in one statement, RAII pattern?
E.g. I've defined a class:
class Somebody{
int age;
string name;
public:
Somebody():age(20),name("dummy"){} // default ctor
Somebody(int a, const char* n):age(a),name(n){} // but I wish to call this ctor
Somebody& operator = (const Somebody& s) {...}
};
Then in main function:
int main(int argc, char const *argv[])
{
Somebody obj(2, "John"); // parameterized ctor
Somebody ar[300]; // initialized, but called default ctor
for(int i=0;i<300;++i){ // initialize again in a loop
ar[i] = ... ; // call operator =
...
Question: could Somebody ar[300] be constructed with parameterized ctor?
If not, then I have to create this object array ar first(Compiler generated code will loop and call default parameter), then apply value changes for each object. This seems quite a bit redundant of cpu cycles.
Is there a way to do what I expected with just one call? (Loop and update each array element with parameterized ctor)
Thanks.
Somebody() : Somebody(20, "dummy") { }to forward the constructor orSomebody(int a = 20, const char * n = "dummy") { }to provide default values for the arguments. That why when you later addint money;you can't accidentally addmoneyin one of the constructors but not the other leading to UB.