Reputation: 3070
I'm trying to loop through a collection of pointers inside the object Baz
from outside the class by having the class return an vector::iterator
. When I run the for
loop I get the following error:
'const class std::unique_ptr' has no member named 'getName'
Can someone explain what's going on and how I can manage to loop through the unique pointer collection inside baz? Thanks in advance.
#include <iostream>
#include <string>
#include <memory>
#include <vector>
class BaseInterface
{
protected:
std::string Name;
public:
virtual ~BaseInterface(){}
virtual void setName( std::string ObjName ) = 0;
virtual std::string getName() = 0;
};
class Foo : public BaseInterface
{
public:
void setName( std::string ObjName )
{
Name = ObjName;
}
std::string getName()
{
return Name;
}
};
class Bar : public BaseInterface
{
public:
void setName( std::string ObjName )
{
Name = ObjName;
}
std::string getName()
{
return Name;
}
};
class Baz
{
protected:
std::vector< std::unique_ptr< BaseInterface > > PointerList;
public:
void push_back( std::unique_ptr< BaseInterface > Object )
{
PointerList.push_back( std::move( Object ) );
}
std::vector< std::unique_ptr< BaseInterface > >::const_iterator begin()
{
return PointerList.begin();
}
std::vector< std::unique_ptr< BaseInterface > >::const_iterator end()
{
return PointerList.end();
}
};
int main( int argc, char ** argv )
{
std::unique_ptr< BaseInterface > FooObj( new Foo() );
FooObj->setName( "Foo" );
std::unique_ptr< BaseInterface > BarObj( new Bar() );
BarObj->setName( "Bar" );
std::unique_ptr< Baz > BazObj( new Baz() );
BazObj->push_back( std::move( FooObj ) );
BazObj->push_back( std::move( BarObj ) );
for( auto it = BazObj->begin(); it != BazObj->end(); ++it )
{
std::cout << "This object's name is " << it->getName() << std::endl;
}
return 0;
}
Upvotes: 3
Views: 1051
Reputation: 126582
You should first dereference your iterator:
std::cout << "This object's name is " << (*it)->getName() << std::endl;
// ^^^^^
Upvotes: 3