I am deriving stl container class vector and trying to overload the [] operators to provide range checking on accessing element with subscript.
But I get compile errors when try to create const object of my derived class Vec
.
For example below is the code:
template<class T>
class Vec : public vector<T>
{
public:
Vec(): vector<T>()
{
}
Vec(int i):vector<T>(i)
{
}
T& operator[](int i)
{
return at(i);
}
const T& operator[](int i) const
{
if(i>=size())
cout<<"error"<<endl;
return at(i);
}
};
void main()
{
Vec<int> v1(10); //works fine
const Vec<int> v(10); //error
}
Why the code const vector v(10); works but const Vec v1(10); doesn't work. Is there something I am missing? Why am I not able to create const object?