Initializing an array pointer using two different constructors

I have a program in which I want to initialize an array of class objects using a 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 constructors in the xyz class. I want to initialize the last two elements using a different constructor, and not the default without arguments. How can i do this?

I want M + 1'th and M + 2'th member to be initialized using another constructor that takes an argument.

+4
source share
2 answers

Firstly, cin<<M is incorrect. It should be cin >> M Make sure your insert and extract statements point in the right direction.

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

Options to achieve your goal: copy the default value for the desired distribution 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 hand-held arrays.

+2
source
 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, of course, is not a safe assumption, and you will have to decide how to handle inappropriate cases.

+4
source

Source: https://habr.com/ru/post/1502906/


All Articles