#include <iostream>
using namespace std;
template <typename T> class Iterator
{
T * ptr;
public:
Iterator(T * addr)
{
ptr=NULL;
ptr=addr;
}
//not working
//virtual Iterator * operator ++(int x);
/*Iterator * operator ++(int x)
{
(this->ptr)++;
return this;
}*/
T operator *()
{
return *ptr;
}
};
template<typename T>
class Vector{
T * a;
public:
Vector(size_t n)
{
a=new T[5];
}
T& operator [](int x)
{
return a[x];
}
class iterator: public Iterator<T>
{
public:
iterator(T * addr): Iterator<T>(addr)
{}
/* not working
Iterator<T> * operator ++(int x)
{
Iterator<T>::ptr++;
return this;
}*/
//working now
iterator * operator ++(int x)
{
Iterator<T>::ptr++;
return this;
}
};
iterator begin()
{
iterator ob(&a[0]);
return ob;
}
};
int main()
{
Vector <char> v(5);
for(int i=0;i<5;i++)
v[i]=i+65;
for(int i=0;i<5;i++)
cout<<v[i]<<endl;
/*~~~~~~ What I want~~~~~~
Iterator <char> p=v.begin();
*/
// what is working now:
Vector<char>:: iterator p=v.begin();
while(*p){
cout<<*p<<endl;
p++;
}
return 0;
}
In the above code, I want to make operator ++() in Iterator class, virtual so that in main I can use:
Iterator <char> ptr=v.begin();
rather than having to use:
Vector <char>:: iterator p=v.begin();
that is a single base class refernce with run time polymorphism to determine which ++ operator to call depending upon whether the value is a vector or list. However, when I declare it virtual in Iterator class it is not working. I have to declare it exclusively for the inner classes, but I want a single interface just like in Java. I am trying to implement the java collection hierarchy in c++ for better structure. What is going wrong? Is it happening because Iterator is a template class which makes return type Iterator also template, that is, the operator ++() function a template function? I know template functions cannot be virtual, only concrete functions can be virtual. What can be done to fix this?