Search code examples
c++inheritancecastingsmart-pointers

SmartPointer : cast between base and derived classes


Say you have a function like this :

SmartPtr<A> doSomething(SmartPtr<A> a);

And classes like this :

class A { }
class B : public A { }

And now I do this :

SmartPtr<A> foo = new B();
doSomething(foo);

Now, I would like to get back a SmartPtr<B> object from doSomething.

SmartPtr<B> b = doSomething(foo); 

Is it possible ? What kind of casting do I have to do ?
Right now, I just found something I believe ugly :

B* b = (B*)doSomething().get()

Important notes : I do not have any access to SmartPtr and doSomething() code.


Solution

  • Instead of doing that, you can do this :

    B *b = dynamic_cast< B* >( doSomething.get() );
    

    but you have to check if b is NULL.