Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

static_cast through inheritance chain that includes a template will fail to compile

In the following example, a upcast with a static_cast will fail to compile:

class B {
public:
    virtual const void func() = 0;
};

template <typename T>
class TB {
public:
    virtual const void func() = 0;
    T var;
};

class D : public TB<double> {
public:
   const void func() {
    std::cout << var << std::endl;
   }
};

int main() {

    D *pd = nullptr;
    B *pbs = static_cast<B*>(pd); // Fails
    B *pbd = dynamic_cast<B*>(pd);

} 

with the error:

error: invalid static_cast from type ‘D*’ to type ‘B*’ in B *pbc = static_cast(pd);

Live example

What is the explanation for this error?

Upvotes: 0

Views: 66

Answers (1)

Brian Bi
Brian Bi

Reputation: 119239

You are getting that error because D isn't actually derived from B, because you forgot to make TB derive from B.

The dynamic cast, however, still compiles because dynamic_cast can do "sideways" casts as well---the cast can actually succeed if the D object is a subobject of some derived class that is also derived directly or indirectly from B. In your example, however, this is not the case, so the cast will just fail at runtime (by returning a null pointer).

Upvotes: 2

Related Questions