I’m trying to create an object in a function, but I am running into the problem that variable names have to be defined at runtime. Is there something I can do like with arrays that allows ne to dynamically create a variable in a function and preferably give it a different name from the one created when the function was called last?
***I’m working in C++
EDIT: I can’t give any code because I don’t have any right now. All I have right now is pseudo code.
Basically, I’m trying to create a linked list, but the addNewItem() method that I want to use would require using the same method to create different objects.
EDIT: Technically, we’re not making a linklist, just more of a proof of concept to understand how they work.
EDIT: Here’s the code:
#include 'linklist.h' #include <iostream> using namespace std; struct linklist { Student * obj; linklist * next; }; linklist * head; int main() { } void addStudent(char * newsdnt) { if(!head){ linklist * a = new linklist; a->obj = new Student(newsdnt); a->next = 0; head = a; return; }else{ linklist * a = new linklist; a->obj = new Student(newsdnt); a->next = 0; if(!head->next){ head->next = a; // Can only have one or two items in list } }
}
If you want a linked list – call new to create each new node and then add it to the list.
Smth like this: