Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ array of objects with const initializer list

Tags:

c++

I have some code like this:

class MyObject {
  private:
    int x;
  public:
    MyObject(int x) : x(x) {}
};

I want to initialize 5 MyObject instances. I know I can do this with g++ 8.3.0.

MyObject obj_array[5]{1, 2, 3, 4, 5};

However, I'm unable to do this:

const int myInts[5] = {1, 2, 3, 4, 5};
MyObject obj_array[5](myInts);

Is there any way to make the second initialization method (initializing array of objects with initialization list constructors using const integer array) work? The rub is that we have a special compiler framework that doesn't allow dynamic memory or most STL datatypes such as vector.

like image 490
tedx Avatar asked Jun 09 '26 05:06

tedx


2 Answers

If we're doing ugly solutions, here's one with scalability:

#define LIST { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
const int myInts[] = LIST;
MyObject obj_array[] = LIST;
#undef LIST
like image 57
M.M Avatar answered Jun 11 '26 20:06

M.M


Not pretty, but this seems to work:

const int myInts[5] = { 1, 2, 3, 4, 5 };
MyObject obj_array[5] = {myInts[0], myInts[1], myInts[2], myInts[3], myInts[4]};
like image 24
selbie Avatar answered Jun 11 '26 19:06

selbie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!