papaiatis papaiatis - 3 days ago 6
C++ Question

In C++ language, how do you create a new object which is a pointer to an array?

I'm using a 3rd party library in which a method is declared this way:

void nexLoop(NexTouch *nex_listen_list[]);


In case of a single
.cpp
file, this is working:

NexButton b0 = NexButton(0, 1, "b0");
NexTouch *nex_listen_list[] =
{
&b0,
NULL
};
...
nexLoop(nex_listen_list);


Full example code can be seen here: https://github.com/itead/ITEADLIB_Arduino_Nextion/blob/master/examples/CompText/CompText.ino

Now I'm incorporating this library in a class which has a separate header and c file, so that:

MyNextion.h

#include "Nextion.h"

class MyNextion {
public:
MyNextion();
void loop();
private:
NexButton *b0;
NexTouch *nex_listen_list[];
}


MyNextion.cpp

#include "MyNextion.h"

MyNextion::MyNextion() {
b0 = new NexButton(0, 1, "b0");
nex_listen_list = new ???
}

MyNextion::loop() {
nexLoop(nex_listen_list); // ???
}


I was messing around with pointers and address operators but I couldn't find the right combination to a successful compilation.

My question is: what would you put here:
nex_listen_list = new ???;


Also, I'm not sure the title well defines my problem. Please correct it if you have a better idea for the title.

Thank you!

Answer

You should not declare a member array without a size. Instead you may declare a pointer-to-pointer:

class MyNextion {
   ...
   private: 
       NexButton *b0;
       NexTouch **nex_listen_list;
};

And then the construction is easy:

nex_listen_list = new NexTouch*[10];
nex_listen_list[0] = b0;
....

That is, nex_listen_list is a dynamic array of pointers to NexTouch objects. And do not forget the delete[] when you are finished:

delete[] nex_listen_list;

That said, I'd rather use a std::vector. Something like:

class MyNextion {
   ...
   private: 
       NexButton *b0;
       std::vector<NexTouch*> nex_listen_list;
};

And then no new or delete required:

nex_listen_list.push_back(b0);
nexLoop(nex_listen_list.data());

And going on, you could declare the b0 as a full object, not a pointer:

class MyNextion {
   ...
   private: 
       NexButton b0;
       std::vector<NexTouch*> nex_listen_list;
};
...
nex_listen_list.push_back(&b0); //use the pointer!

No new so no delete and no leaks.

Comments