On Sep 22, 5:32 am, jarek <ja...@nospam.plwrote:
Hi!
How can I declare iterator to const object ?
I've the following:
class ClassA : public list<ClassB>
{
....
}
somefunction( const Class A *obj )
{
ClassA::iterator it; // <- this is wrong....
it = obj->begin();
....
}
regards
J.
1. deriving from containers is not usually the right thing to do, use
composition instead
2. use a reference_to_constant instead of a
mutable_pointer_to_constant
void foo( const A* obj ) { } // ptr can be reseated
void foo( const A* const obj ) { } // better
void foo( const A& obj ) { } // perfect
3. An iterator implies a type that can mutate its target. You can't
mutate a const target, so
const_iterator is required to obtain read only access.
Perhaps something like:
#include <iostream>
#include <list>
class B { };
class A
{
std::list< B m_list;
public:
typedef std::list< B >::const_iterator const_iterator;
const_iterator begin() const
{
return m_list.begin();
}
const_iterator end() const
{
return m_list.end();
}
void push_back( const B& r_b )
{
m_list.push_back(r_b);
}
std::size_t size() const
{
return m_list.size();
}
};
void somefunction( const A& r_a )
{
for( A::const_iterator it( r_a.begin() );
it != r_a.end();
++it )
{
std::cout << &(*it) << std::endl;
}
}
int main()
{
A a;
B b;
a.push_back(b);
a.push_back(b);
std::cout << "size: ";
std::cout << a.size() << std::endl;
somefunction( a );
}