views:

103

answers:

4

I have a list of type Instruction*. Instruction is a class that I made. This class has a function called execute().

I create a list of Instruction*

list<Instruction*> instList;

I create an Instruction*

Instruction* instPtr;
instPtr = new Instruction("test",10);

If I call

instPtr.execute();

the function will be executed correctly, however if I store instPtr in the instList I cannot call the execute() function anymore from the list.

//add to list
instList.push_back(instPtr);

//create iterator for list
list<Instruction*>::iterator p = instList.begin();
//now p should be the first element in the list
//if I try to call execute() function it will not work
p -> execute();

I get the following error:

error: request for member ‘execute’ in ‘* p.std::_List_iterator<_Tp>::operator-> [with _Tp = Instruction*]()’, which is of non-class type ‘Instruction*’
+3  A: 

try (*p)->execute();

Alex Deem
Sadly (well, actually it's probably a good thing) you can't use `p->->execute();` for this
Sumudu Fernando
+1  A: 

Instead of p->execute() you need (*p)->execute();

You need to de-reference the list iterator to get the value associated with the node in the list referenced by your iterator.

sdtom
+7  A: 

p is an iterator of Instruction * pointers. You can think of it as if it were of type Instruction **. You need to double dereference p like so:

(*p)->execute();

*p will evaluate to an Instruction *, and further applying the -> operator on that will dereference the pointer.

John Kugelman
A: 

The best solution is keep boost::shared_ptr in your list. Remember all STL containers working with copy principle.

Use this code

list > instList;

then call your execute function as usual

instList[i]->execute();

as you can see you call execute as you keep pointers in your list. this is the best solution

Davit Siradeghyan
The question is not about resource management. Your code works only because you used the std::list::operator[]
Oren S
who asked that I cannot use this operator and why???
Davit Siradeghyan
I didn't say you cannot use it. The problem the OP had had nothing to do with the pointer type. It was having dereferenced the iterator only once instead of twice. your solution dereferenced the iterator twice: once by calling operator[] and the other by using ->. It would have worked even if you used a built-in pointer just the same (although not doing what the OP requested: using begin())
Oren S