user1519221
user1519221

Reputation: 639

Pointer list c++

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.

Upvotes: 3

Views: 38910

Answers (4)

villekulla
villekulla

Reputation: 1085

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.

Upvotes: 2

TASagent
TASagent

Reputation: 244

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.

Upvotes: 1

P0W
P0W

Reputation: 47854

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

So use :

(*it)->printHello();

Upvotes: 1

Daniel Frey
Daniel Frey

Reputation: 56921

You want

(*it)->printHello();

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

Upvotes: 6

Related Questions