Reputation: 496
I'm trying to iterate through a std::list
(containing) objects and print some methods but the compiler complaints that
'print': is not a member of 'std::shared_ptr<A>'
However if i create an object std::shared_ptr<A> animal(*it);
and call animal.print()
it will work just fine why is that? below is the function i'm having trouble with (it's also a small portion of my very large program involving lots of polymorphism)
friend std::ostream& operator<<(std::ostream& out, const Hand& _hand) {
std::list< std::shared_ptr<A>>::const_iterator it = _hand.hand.begin();
std::shared_ptr<A> animal(*it);
animal.print(); //workss
while (it != _hand.hand.end()) {
it->print(); //doesn't work
++it;
}
return out;}
The list
i'm iterating through is of type A
(which is abstract) and contain objects of it's derived classes.
Upvotes: 1
Views: 779
Reputation: 21763
(*it)
returns a smart pointer reference, so you need to dereference it again.
(**it).print()
or (*it)->print()
Or you may find this neater if you want to call several functions in a row: const auto& animal = **it; animal.print();
Upvotes: 3