Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to add a base class to a vector of derived classes
    primarykey
    data
    text
    <p>I have a <code>std::vector</code> that holds shared pointers to a derived class <code>cDerivedClass</code>, I also have shared pointers for the base class too. So something like this:</p> <pre><code>typedef SHARED_PTR&lt;cBaseClass&gt; cBaseClassPtr; typedef SHARED_PTR&lt;cDerivedClass&gt; cDerivedClassPtr; std::vector&lt;cDerivedClassPtr&gt; vDerivedPtrList; </code></pre> <p>Now if I want to have a <code>CDerivedClass::AddComponent(cBaseClassPtr inpBaseClass)</code> method that takes an argument of type cBaseClassPtr and adds it to the vector (vDerivedPtrList) of derived classes, how would I go about doing this? </p> <p>I know dynamic_cast won't work since base-to-derived conversions are not allowed with dynamic casts unless the base class is polymorphic. I've tried static casting the cBaseClassPtr to a cDerivedClassPtr, but I'm thrown an error. </p> <pre><code>void cDerivedClass::AddComponent(cBaseClassPtr inpBaseClass) { MY_ASSERT(inpBaseClass, "Component cannot be NULL"); cDerivedClassPtr pDerviedPtrToAdd = static_cast&lt;cDerivedClassPtr&gt;(inpBaseClass); this-&gt;mvComponentList.push_back(pDerviedPtrToAdd); } </code></pre> <p>Edit: To be exact this is the error I'm getting:</p> <pre><code>No matching conversion of static_cast from 'cBaseClassPtr' (aka 'shared_ptr&lt;cBaseClassPtr&gt;') to 'cDerivedClassPtr' (aka 'shared_ptr&lt;cDerivedClassPtr&gt;'); </code></pre> <p>I'm using boost's implementation of smart pointers<a href="http://www.boost.org/doc/libs/1_42_0/libs/smart_ptr/shared_ptr.htm" rel="nofollow"><code>boost::shared_ptr</code></a></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload