I'm just starting to work with classes in arduino, and I'm having some trouble figuring out a small issue in my code.
I am currently trying to write a custom menu system for a project I'm working on (to display on an LCD) and thought I would try using classes to handle the creation of submenus within the system.
To create a submenu, I would like to call the menu constructor and pass in a few values along with an array, which would contain all the items to be displayed within the menu.
The issue I'm currently running into is that the constructor does not seem to like getting an array passed in the way I am doing it.
Here is the code:
String mainMenuItems[] =
{
"Option 1",
"Option 2",
"Option 3"
};
class Menu
{
int menuID;
int tier;
int menuLength;
String menuItems[];
public:
Menu(int id, int lvl, int numItems, String items[])
{
menuID = id;
menuItems = items;
tier = lvl;
menuLength = numItems;
}
};
Menu main(1, 1, 3, mainMenuItems);
The error I get is:
error: incompatible types in assignment of 'String*' to 'String [0]'
menuItems = items;*
^* exit status 1 incompatible types in assignment of 'String*' to 'String [0]'
How can I change this to properly pass an array to the Menu constructor? Note that I'd like the passed array to be any size.
Passing an entire array to a function is not permitted in C++, so when the compiler sees you trying, it instead passes a pointer to the first element of the array.
your constructor should expect a pointer to an array, if you insist on trying to pass the array.
Menu(int id, int lvl, int numItems, String* items)
you should (and you may hear this from a bunch of folks) abandon String class in favor of using null-terminated char arrays (C strings).
All that said, it isn't clear what you are actually trying to do here.
BulldogLowell:
Passing an entire array to a function is not permitted in C++, so when the compiler sees you trying, it instead passes a pointer to the first element of the array.
your constructor should expect a pointer to an array, if you insist on trying to pass the array.
Menu(int id, int lvl, int numItems, String* items)
you should (and you may hear this from a bunch of folks) abandon String class in favor of using null-terminated char arrays (C strings).
All that said, it isn't clear what you are actually trying to do here.
That won't solve his problem. In fact, it won't change anything at all, since the compiler already treats items as being of type (String *). His problem is he is trying to assign (String *)items (a pointer to an array of String objects) to (String)menuItems (an actual array of String objects). The type of menuItems needs to be changed to
String *menuItems;
and all will be well. He can treat menuItems as a pointer to an array of String objects, and all will work as it should.