static_cast vs. dynamic_cast and reinterpret_cast
Let's suppose I have an array of a base class, but it's filled with derived classes. I'll use only one derived class, but suppose there are several types.
Code:
Edit: wrong! CBase myArray[MY_ARRAYSIZE];
What I meant: CBase *myArray[MY_ARRAYSIZE];
...
reinterpret_cast<CDerived *>(myArray[i])->derivedFunction();
According to the descriptions of the various castings, this is the wrong thing to do since it doesn't "climb the trees" to return the correct pointer (where a pointer to the derived might actually != pointer to the same object's base!)
So I'd want to use dynamic_cast or static_cast instead (static_cast would be good enough for this particular application.)
More importantly, reinterpret_cast is wrong to use in this situation always?
Re: static_cast vs. dynamic_cast and reinterpret_cast
Quote:
Originally posted by Gorgor
Code:
CBase myArray[MY_ARRAYSIZE];
That doesn't make sense. If you have an array of base class objects, then they are base class objects and not derived class objects. Since the derived class generally will be larger in size than the base class, there's no way you could be putting derived class objects into the array that your compiler created full of base class objects.
If you want an array of base class objects whose type is actually of a derived class, you'd need an array of pointers to base, and then you could use the dynamic_cast to get the appropriate derived object later:
Code:
CBase* myArray[MY_ARRAYSIZE];
for (int i = 0; i < MY_ARRAYSIZE; i++)
myArray[i] = new CDerived;
// ...
CDerived* myDerivedPtr = dynamic_cast<CDerived*>(myArray[j]);
if (myDerivedPtr)
myDerivedPtr->DerivedFunction();