Search code examples
c++undefined-behaviordowncaststatic-cast

Example of useful downcast with static_cast which does not produce undefined behaviour


I am wondering about a short code example of an application of downcast via static_cast, under conditions where there is no undefined behaviour. I have looked around and I found quite a few texts (posts, Q&A, etc.) referring to fragments of the standard, explaining, etc. But I found no examples that illustrate that (and that surprises me).

Could anyone provide one such example?


Solution

  • A very basic example:

    class Animal {};
    class Dog : public Animal {};
    
    void doSomething() {
      Animal *a = new Dog();
      Dog *d = static_cast<Dog*>(a);
    }
    

    A more contrived example:

    class A { public: int a; };
    class B : public A {};
    class C : public A {};
    class D : public B, public C {};
    
    void doSomething() {
      D *d = new D();
      int bValue = static_cast<B*>(d)->a;
      int cValue = static_cast<C*>(d)->a;
    
      // This does not work because we have two a members in D!
      // int eitherValue = d->a;
    }
    

    There are also countless other cases where you know the actual type type of the instance due to some flags or invariants in your program. However, many sources recommend preferring dynamic_cast in all cases to avoid errors.