How to dynamic cast the pointer to the vector of elements of the base class to the vector of derived class

Viewed 116

I have the Base class and the A class derived from Base.

Also I have the B class and I want to pass the pointer to the vector of elements of the Base class 'std::vector *ptrVec' to the B constructor and then cast ptrVec to the vector of elements (or to the pointer to vector of the elements) of the derived class A.

It seems I can solve this when I am passing 'std::vector<Base *> *ptrVec' as the second argument of the B constructor. But I don't want to use the pointer to the vector of pointers because by doing it I have to allocate dynamic memory before with 'new' operator. I would use unique_ptr or shared_ptr here but I'm not good enough with smart pointers yet and I'll be glad if anyone show me

I can try to describe my problem in more detail if needed

class Base
{
public:
    virtual ~Base() {}
};

class A : public Base
{
public:
    A() {}
    ~A() {}
};

class B
{
public:
    B(Base *singleObjectPtr, std::vector<Base> *ptrVec)
    {
        m_singleObj = dynamic_cast<A *>(singleObjectPtr); // casting for single object
    
        // how to dynamic cast std::vector<Base> * to std::vector<A> * ?
        // ...
    
        /*
        // In case I have  [std::vector<Base *> *ptrVec]  instead of  [std::vector<Base> *ptrVec]
        // as the second parameter of B constructor I would do smth like
        for(int i = 0; i < ptrVec->size(); ++i)
        {
            m_ptrVec.push_back( dynamic_cast<A *>( ptrVec->at(i) ) );
        }
        // and in the 'protected' section of B add 'std::vector<A *> m_ptrVec;' instead of 'std::vector<A> *m_ptrVec;'
        // but I also don't like copying elements here
        // maybe I can use smart pointers here but I don't know how
        */
    }
    ~B() {}

protected:
    A *m_singleObj;
    std::vector<A> *m_ptrVec;
};

I can cast single object, but I need to cast the entire vector

class B
{
public:
    B(Base *singleObjectPtr/*, vector of Base elems */)
    {
        m_singleObj = dynamic_cast<A *>(singleObjectPtr);
        std::cout << "B constructor says: m_singleObj.a = " << m_singleObj->getA() << std::endl;
        // dynamic cast for vector...
        // working with each element of casted vector
    }

protected:
    A *m_singleObj;
    std::vector<A *> m_ptrVec; // or another proper declaration
};

int main()
{
    A justA(5);
    std::cout << justA.getA() << std::endl;
    B justB(&justA);
    
    // creating and passing a vector of pointers to the A elements to the B constructor

    return 0;
}
0 Answers
Related