C++: Throwing shared_ptr of derived and catching shared_ptr of base?

Posted by hasvn on Stack Overflow See other posts from Stack Overflow or by hasvn
Published on 2012-03-30T09:15:48Z Indexed on 2012/03/30 11:29 UTC
Read the original article Hit count: 130

Filed under:

Ok, I've been told this problem: Why can you throw a pointer to a derived class and catch a pointer to its base... but you can't do that with shared_ptrs?

Example, this works:

class Base {};
class Derived : public Base {};
int main()
{   
    try 
    {   
        throw new Derived() ;
    }   
    catch( const Base2 * b ) 
    {   
        printf("Received a base" ) ; 
    }   

    return 0 ;
}

But this doesn't

int main()
{
    try
    {
        throw std::tr1::shared_ptr<Derived>( new Derived() ) ;
    }
    catch( const std::tr1::shared_ptr<Base> & b ) 
    {
        printf("Received a base" ) ;
    }
    return 0 ;
}

Any ideas?

© Stack Overflow or respective owner

Related posts about c++