Rishabh876
Rishabh876

Reputation: 3190

initializing pointer to array with two different constructor

I have a program in which i want to initialize an array of class objects using pointer.

class xyz{};
cin>>M;

xyz *a=new xyz[M];   //this will call the constructor for each object.

the problem is that i have two constructor in class xyz. i want to initialize last two element using other constructor, not the default one with no arguments. how can i do this?

i want M+1'th and M+2'th term to be initialized by different constructor that accepts argument.

Upvotes: 4

Views: 1375

Answers (2)

Zac Howland
Zac Howland

Reputation: 15870

First, cin<<M is wrong. It should be cin >> M. Make sure your insertion and extraction operators are pointing the correct direction.

You cannot with single indirection. The new operator will call the default constructor for each object in the array.

Options for how to reach your goal are: copy the default value you want over the desired allocation, or create an array of pointers to objects.

Copy Method

xyz t(my_other_constructor);
xyz* a = new xyz[M];
a[M - 1] = t; // overwrite the default constructed value with the desired

Double Indirection

xyz** a = new xyz*[M];
for (int i = 0; i < M - 1; ++i)
{
    a[i] = new xyz;
}
a[M - 1] = new xyz(my_other_constructor);

Ideally, you would use std::vector instead of creating manual arrays, though.

Upvotes: 2

Benjamin Lindley
Benjamin Lindley

Reputation: 103751

std::vector<xyz> a(M-2);
a.push_back(xyz(...));     // xyz(...) here is a call to the
a.push_back(xyz(...));     // constructor you want to use

This code assumes that M >= 2. This is, of course, not a safe assumption, and you will have to decide how to handle non-conforming cases.

Upvotes: 4

Related Questions