My problem is the use of const_cast<>. I have a class which inherits from vector. Now in one of its member functions when I use this->begin()
, this
being a const pointer, it returns a constant iterator but I want to obtain a non-const iterator. The code looks something like ...
class xyz : private std::vector<//something>
{
public:
xyz();
void doSomething();
}
void doSomething()
{
xyz::iterator it;
it = this->begin();
*it.insert(something); //here is the problem and this where I need to use const_cast
// and in a lot more places
}
In the above function, since this->begin()
returns a const iterator, I am forced to use a constant iterator and do a typecasting whenever I need to insert an element.
I thought of using const_cast at this->begin() but my friend told me that it is a bad idea to remove the constness of the this
pointer. If it is so, then what is the way around?