wendazhou
wendazhou

Reputation: 305

Casting between shared_ptr of forward declared class hierarchy

I have a class manipulating only shared_ptr to an inheritance hierarchy (quite simple, there are a few classes, say A, B, C etc. inheriting from a single class Base). Since I do not need to manipulate the instances of A, B, C... themselves, they are only forward declared. However, the compiler chokes when I try to pass a shared_ptr<A> to a method taking a shared_ptr<Base>, since the compiler does not know that A inherits from Base. Is there any other way than either static_pointer_castor #includethe header of class A? And if not, which one would you choose?

EDIT: adding some code

// in some file: (Base.h)
class Base
{
    /*code*/
}

// in another file (A.h)
class A : public Base
{
}

// in my file (impl.cpp)
class A; // forward declaration    

void Dummy()
{
    std::shared_ptr<A> myPtr;

    // we have somewhere: void sillyFunction(shared_ptr<Base> foo)
    sillyFunction(myPtr); // does not compile, as no conversion is found.
}

Upvotes: 1

Views: 389

Answers (1)

jpalecek
jpalecek

Reputation: 47770

Is there any other way than either static_pointer_castor #includethe header of class A?

No. In fact, the #include is the only way to do it properly (static_pointer_cast either wouldn't work or invokes undefined behavior). You can't cast ordinary pointers between incomplete subclass and superclass, either.

Upvotes: 1

Related Questions