I have a task in my c++class which involves these functions, and i cant change the arguments.
Its part of a linked list. The data is a const Monster*. The problem comes when i have a function that has to return a non const Monster*.
1 2 3 4 5 6 7 8 9 10
//Here i am forced to use const Monster* in the list. I add it to a node.
void MonsterDB::add(const Monster& entry){ first = new MonsterDBNode(first, entry); }
//Here i am to return a non-const pointer to the object, but it cant.
Monster* MonsterDB::find(const std::string& name){
for (MonsterDBNode *p = first; p; p = p->next)
{
if (p->data->name == name) return p->data;
}
}
Am i doing something wrong? I get a reference to an object created in a test program supplied by the teacher(the teacher's supplied function's argument's demand a const object, so thats what i use in my list), i create a node which has a pointer to that referenced object. I then try to return that pointer by this call in the teachers test program.:
Later this returned object is to be passed back into a function that deletes that object from the list, so i don't think i can just create a new object and send that back.
You are not forced to store const objects in the list - I am pretty sure you are expected to create new objects by copying the const parameter you are given. This is how std::vector works for push_back().
I have tried that, but haven't found the solution for the problem that comes from that either. I can't add the supplied const Monster to the node, are you saying i should create a yet new Monster?
Thanks, that worked and i managed to fix some problems regarding that change. All the pointer and references stuff gets confusing when I'm coming from java.
In modern C++, pointers are rarely used. Unfortunately, classes that teach C++ aren't exactly modern (and sometimes even teach C while pretending it's C++).