How to allocate memory dynamically for class using new in C++?

Since you say you need to use new directly, then you can do it easily for ten separate objects:

mem * mem1 = new mem(42);
// and so on

You can’t specify initialisers when allocating an array with new; you’ll have to let them be default-initialised, then reassign them:

mem * mems = new mem[10];
mems[0] = mem(42);
// and so on

Don’t forget to assign them to smart pointers (or delete them when you’ve finished with them, if the weird requirement to use new also forbids other forms of sensible memory management).

When you find yourself working under less insane restrictions, use std::array or std::vector instead of mucking around with raw memory allocations:

std::vector<mem> mems = {42, 63, /* and so on */};

Leave a Comment