zhangzhimin zhangzhimin - 4 months ago 14
C++ Question

How can I cast a base smart pointer into the derived one in C++?

Code :

class Base {
...
};

class Derived : public Base {
void OnlyOwnedByDerived{
...
}
};


The question is :
1. If I used a smart pointer of the Base class to reference the Derived one, the reason why I do so is that I want to get the benefit of dynamic binding which only fits virtual functions. But if I want to to use the function that is only owned by the derived class, what should I do ?
static_cast
between the smart pointer of different class gives me an error...


  1. The most direct way I can come up with is use raw pointer rather than smart one...


Answer

In C++11, there is the dynamic_pointer_cast

Which you can use:

void func(std::shared_ptr<Base> b){
    b->VirtualBaseFunction();
    if(auto d = dynamic_pointer_cast<Derived>(b)){
         d->DerivedSpecificFunction():
         ....more code
    }
}