I would like to be able to add CObject derived objects to CArrayObj, but overload the [] operator to return the pointer of the derived object instead of CObject*
class MyArrayObj : public CArrayObj
{
public:
CObject *operator[](const int index) const {return (CObject*)At(index);}
};
Similar to this but instead of returning the CObject pointer, I would first like to cast it to the derived object. So if I had…
class A : public CObject
{
public:
void Print() { ::Print("I am A");}
};
class B : public CObject
{
public:
void Print() { ::Print("I am B");}
};
… and I added them to the array…
A *a = new A;
B *b = new B;
MyArrayObj array;
array.Add(a);
array.Add(b);
…and I referenced the index…
for(int i=0;i<array.Total();i++)
array[i].Print();
… it would dynamically cast the derived class to the [] operator. For example…
array[i].Print()
// would be the equivalent to
((A*)array.At(i)).Print();
// if the object is A type OR
((B*)array.At(i)).Print();
//if the object is B type
…where the returned pointer is automatically resolved and casted to the objects original type.
I know I can use polymorphism to accomplish this, but I don’t want to rewrite the standard lib…