Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ converting reference to base pointer to reference to derived pointer

I have this problem:

// the classes
class cBase {};
class cDerived : public cBase {};

class cBaseArray
{
    // the array of pointers to cBase
    cBase** array;

    // overloaded operator that returns an element of the array
    cBase*& operator[](unsigned index)
    {
        // much more complicated, but simplified for example
        return array[index];
    }
};

class cDerivedArray : public cBaseArray
{
    // overloaded operator that returns a converted element of the array
    cDerived*& operator[](unsigned index)
    {
        // conversion required, but don't know how
        return static_cast<???>(cBaseArray::operator[](index));
    }
};

So how do I convert the reference to pointer to cBase returned by the operator[] of cBaseArray to refernce to pointer to cDerived that can be returned by the operator[] of cDerivedArray?


1 Answers

You have to dynamic_cast them.

like image 153
Paul Evans Avatar answered Mar 02 '26 09:03

Paul Evans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!