I’m defining iterator types for my container and of course I want iterator to be convertible to const_iterator. But I’m not sure which is better/preferable:
Conversion operator in iterator
class iterator
{
operator const_iterator();
};
or non-explicit constructor in const_iterator
class iterator
{
// implementation
friend class iterator; // hard to avoid this
};
class const_iterator
{
const_iterator(iterator const &);
};
Are there any guidelines which way is better?
You should write a casting operator only if it is possible to return the desired type without constructing a new object, or if its return is a simple data type. For example, if it were to return a const reference to a property within the class, then you should write it as a casting operator.
In all other cases, you should just write the appropriate constructor.