2

This might be a simple question but I am trying to initialize an array of objects using a parameterized constructor. For example:

class A{
public:
    int b,c,d;
    A (int i, int j);
};

void A::A(int i, int j){
    d = rand()
    b = 2*i;
    c = 3*j;
}

void main(){
    A a[50]; /*Initialize the 50 objects using the constructor*/
}

I have already tried with vector initialization as mentioned in this link however, since there are 2 parameters, this does not work.

Also, as mentioned in this link, it is not possible and tedious to manually enter 50 initialization values.

Is there a easier way. Also, i,j values are the same for all objects (available through main()) but d should be random value and differs from each object.

2 Answers 2

2

You can use std::generate

Example:

A generator(){ return A(1,2); }

std::generate( a, a + (sizeof(a) / sizeof(a[0])), generator );
Sign up to request clarification or add additional context in comments.

2 Comments

Good luck with that in C++03! (No lambdas until C++11).
Yes, I forgot this. Updated
0

Why not supply default arguments to your two-argument constructor?

A (int i = 0, int j = 0);

Then it will stand in for the default constructor, and A a[50]; will use it automatically 50 times.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.