Trouble with const, references, pointers, returns

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.:

1
2
//This Monster isn't const.
Monster *entry = db.find("Hodor");


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?
No, you should make the copy at the end of the call stack - that is, from within your node constructor.
Neither works, am i missing something special in c++?
1
2
3
4
5
6
MonsterDBNode(MonsterDBNode *n, Monster *d) : next(n), data(d) {};

MonsterDBNode::MonsterDBNode(MonsterDBNode *n, Monster *d){
	next = n;
	data = d;
}


The complete node:
1
2
3
4
5
6
7
class MonsterDBNode{
public:
	MonsterDBNode(MonsterDBNode *n, Monster *d) : next(n), data(d) {};
	Monster *data;
	MonsterDBNode *next;
};

1
2
3
4
5
6
class MonsterDBNode{
public:
	MonsterDBNode(MonsterDBNode *n, Monster const &d) : next(n), data(d) {};
	Monster data;
	MonsterDBNode *next;
};
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++).
Yeah, most courses are most likely using not up to date stuff since they are usualy not part of the frontline.
Last edited on
Topic archived. No new replies allowed.