IN CPPHow can we pass arguments to the constructor of a dynamically allocated array of classes? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

IN CPPHow can we pass arguments to the constructor of a dynamically allocated array of classes?

let entity be a class then, entity* e_ptr[4]={????}; how to pass args to the class ctors and how to call the methods of the class using the e_ptr?

2nd Mar 2018, 4:53 PM
Melodemon Alpheus
Melodemon Alpheus - avatar
1 Answer
+ 6
You are declaring a 2D array here, right? Now, you may use {} to call individual constructors, but I don't know if they will work for pointers as well. So if you had : class e { int a,b; e(int r,int s):a(r),b(s){} void print() { cout<<a+b<<"\n"; } }; You could do : e myarr[4] = { {1,1},{2,2},{3,3} }; // Works for any type. And then to call the members : for(int i=0;i<4;i++) myarr[i].print(); Now, in your case the elements are pointers and so the above loop will use a -> instead of a dot.
2nd Mar 2018, 5:31 PM
Kinshuk Vasisht
Kinshuk Vasisht - avatar