Luc Aux Luc Aux - 5 months ago 54
C++ Question

Initializing and allocating dynamic memory in the same constructor

So assuming I have these private data members of a class in a .h file

eventlist *pointer;
int counter;
int size;

and this struct type

struct eventlist// Define our struct type
char name[100];
char todo[100];
char where[100];
char when[100];
char attended[100];
char excitement[100];

And I want to create a dynamic array of structs. Here is what I have as a constructor...

size = 0;// Initialize size to zero
counter = 0;//Initialize counter to zero
pointer = new eventlist[size];



I am mostly curious about:

  1. Is it okay to allocate my array of structs in my constructor? Could it cause any problems?

  2. Is it okay to allocate the array before initializing the pointer to NULL? I am assuming it is not a big deal since I am in a way initializing it as a pointer to a dynamic array. But I want to know if it is an acceptable practice.

  3. Does it make sense to initialize the first element of the array like the way I did? I thought since the memory is allocated for at least one element of the array (the base) it'd be a good practice to initialize the first element, but I am still a little shaky whether I am visualizing correy.

  4. Lastly, after I created my dynamic array and I set pointer to = NULL, that would just create a memory leak, and wouldn't initialize the first element right?

Answer Source
  1. Yes this is fine, in fact allocating in the constructor and deleting in the destructor is the start of RAII types which you should aim to achieve.
  2. You are simply assigning a pointer to some memory, it does not matter what the pointer held before, it could be anything.
  3. That depends entirely on your application.
  4. Yes you would. You need to delete any memory you have created. I would suggest in the destructor of your class. Remember to match new[] with delete[].

As a final note, this type of code is good for learning, but bad for implementation in c++. Unless you have some form of memory restriction (which you clearly don't since you are creating a big set of dynamic stored structures) then you should switch to using some of the built in c++ types, like std::vector to replace your dynamic array, and std::string to replace your char arrays.

struct eventlist {
    std::string name;

class summerlist {


    std::vector<eventlist> pointer;
    int counter; 

    counter = 0;// Initialize the counter to zero

This is much easier to use and control. And you avoid the mistake of doing this: pointer = new eventlist[size]; where size is 0. This should save you some headache.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download