3

The code below:

#include <iostream>
#include <list>
class A
{
    public: 
    void printHello(){std::cout << "hello";}
};
int main(int argc, char *argv)
{
    std::list<A*> lista;
    lista.push_back(new A());
    for(std::list<A*>::iterator it=lista.begin();it!=lista.end();++it)
    {
        //how to get to printHello method?
        //it doesn't work
        it->printHello();       
    }   
    return 0;
}

This code doesn't work. My question is how to get to method 'printHello' by iterator it? Thanks.

user1519221
  • 631
  • 5
  • 13
  • 24

4 Answers4

6

You want

(*it)->printHello();

as the *it returns the stored pointer A* and only then you can apply ->.

Daniel Frey
  • 55,810
  • 13
  • 122
  • 180
2

Just change following line

it->printHello(); 

to

(*it)->printHello(); 

The operator*() gives access to the contained data of the container, which in your case is a pointer. When not using pointers in containers, just using operator->() would work, too.

villekulla
  • 1,039
  • 5
  • 15
1

De-referencing it will give you pointer to A, then you need to access the methods or data members.

So use :

(*it)->printHello();

P0W
  • 46,614
  • 9
  • 72
  • 119
1

Let me expand on Daniel's answer.

When you stick an asterisk in front of a variable, it is called 'dereferencing'. Used this way, the Asterisk is a 'Dereference Operator'. To put it noob-ishly (I don't know what level of understanding you have offhand), *pMyPointer acts like it was the Object that the pMyPointer was pointing to. If it was a Pointer to a Pointer, then the result is just the Pointer.

As an example, when you call a method on a pointer, you use the Into Operator ->.

These two often do the same thing:

pMyPointer->MyFunction();

(*pMyPointer).MyFunction();

In the case of the C++ iterators, the Dereference Operator is overwritten to return the object stored in its position. In this case, what is stored in its position is a pointer, so you still have to use -> unless you stick another Dereference Operator in there.

TASagent
  • 244
  • 1
  • 7