English

C++ Performance Deep Dive: Type Conversions

4/20/2026
19
C++ Performance Deep Dive: Type Conversions


C++ provides a variety of casting operators, each suited for different scenarios. This article explores best practices for type casting.

Note: usually we need to avoid downcast. but if must need then you can read this article.


Here are all cast methods in C++:
1. C-style cast - (Type) expression, Not recommended in modern C++ since not safe.

2. static_cast - Compile-time safe cast, No runtime check, zero overhead.

3. dynamic_cast - Runtime type-checked cast,Small runtime overhead (vtable lookup) but Safe downcasting; returns nullptr on failure, Requires polymorphic type (virtual function)

4. const_cast - Cast to modify const / volatile qualifier

5. reinterpret_cast - Reinterpret memory bit pattern,Extremely unsafe, for system/low-level programming only

6. static_pointer_cast - Shared pointer version of static_cast

7. dynamic_pointer_cast - Shared pointer version of dynamic_cast

8. const_pointer_cast - Shared pointer version of const_cast

As const_cast and reinterpret_cast have fairly explicit use cases, we shall omit their discussion and concentrate primarily on dynamic_cast and static_cast.

First, let's take a look at an example:

C++
#include "iostream"

class Shape {
    public: 
    virtual ~Shape() = default;
    virtual void draw() = 0;
};

class Circle : public Shape {
    public:
    void draw() override {
        printf("Circle::draw()\n");
    }
};

class Rectangle : public Shape {
    public:
    void draw() override {
        printf("Rectangle::draw()\n");
    }
};

int main() {
    // Create a pointer to Circle object and assign it to a pointer to Shape object.
    Circle * a = new Circle();
    Shape * b = a;
    b->draw();

    // Downcast it to the right class Circle.
    Circle *c = static_cast<Circle *>(b);
    c->draw();
    
    // Downcast it to the right class Rectangle.
    Rectangle *d = static_cast<Rectangle *>(b);
    d->draw();
}

We are able to compile and run the code successfully. however, it is clear that here is a logical error in it. In fact, pointer b originally points to a Circle object. Nevertheless, using static_cast to convert it into a pointer to Rectangle causes no compilation error at all.

This is the inherent drawback of static_cast. it is a compile-time cast, which permits conversion as long as the target type lies within the inheritance hierarchy of the original type.

To avoid such errors. we can instead perform type conversion with dynamic_cast. since it conducts runtime validation via the v-table.

The modified code is shown below.

C++
#include "iostream"

class Shape {
    public: 
    virtual ~Shape() = default;
    virtual void draw() = 0;
};

class Circle : public Shape {
    public:
    void draw() override {
        printf("Circle::draw()\n");
    }
};

class Rectangle : public Shape {
    public:
    void draw() override {
        printf("Rectangle::draw()\n");
    }
};

int main() {
    // Create a pointer to Circle object and assign it to a pointer to Shape object.
    Circle * a = new Circle();
    Shape * b = a;
    b->draw();

    // Downcast it to the right class Circle.
    Circle *c = dynamic_cast<Circle *>(b);
    c->draw();
    
    // Downcast it to the right class Rectangle.
    Rectangle *d = dynamic_cast<Rectangle *>(b);
    d->draw();
}

The code still compiles successfully, yet a segmentation fault occurs at runtime. 

This is because the conversion dynamic_cast<Rectangle*>(b) fails, leaving pointer d as a nullptr. thus, the program crashes when d->draw is called in the next line.

Although dynamic_cast guarantees safe type conversion, it introduces additional runtime overhead. in contrast, static_cast has zero runtime overhead but can not ensure conversion safety.

So how can we achieve both conversion safety and zero runtime overhead?

One solution is presented below (refer to muduo library):

C++
#include "iostream"
#include "assert.h"

#define NDEBUG


class Shape {
    public: 
    virtual ~Shape() = default;
    virtual void draw() = 0;
};

class Circle : public Shape {
    public:
    void draw() override {
        printf("Circle::draw()\n");
    }
};

class Rectangle : public Shape {
    public:
    void draw() override {
        printf("Rectangle::draw()\n");
    }
};

template<typename To, typename From>
inline To implicit_cast(From const &f)
{
  return f;
}


template<typename To, typename From>     // use like this: down_cast<T*>(foo);
inline To down_cast(From* f)                     // so we only accept pointers
{
  // Ensures that To is a sub-type of From *.  This test is here only
  // for compile-time type checking, and has no overhead in an
  // optimized build at run-time, as it will be optimized away
  // completely.
  if (false)
  {
    implicit_cast<From*, To>(0);
  }

#if !defined(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI)
  assert(f == NULL || dynamic_cast<To>(f) != NULL);  // RTTI: debug mode only!
#endif
  return static_cast<To>(f);
}

int main() {
    Circle * a = new Circle();
    Shape * b = a;
    b->draw();

    // 
    Circle *c = down_cast<Circle *>(b);
    c->draw();

    Rectangle *d = down_cast<Rectangle *>(b);
    d->draw();

    return 0;
}

This is a classic, high-performance utility for safe downcasting in C++. It is designed to bridge the gap between compile-time safety, debug-time correctness, and runtime efficiency.

1. The implicit_cast ensure that the compiler to verify that To is a subclass of From (or the same type). if(false) will be optimized by compiler since it will never be executed but the compile time validation still happened.

2. In debug builds (NDEBUG not defined) and if RTTI is enabled, it uses dynamic_cast to check if f actually points to an object of type To.

3. In release builds, it uses static_cast to ensure zero runtime overhead.

Since C++ 11,we can use type trait and static_assert to ensure To must be derived from From classes at compile time.

C++
#include "iostream"
#include "assert.h"
#include <type_traits>

#define NDEBUG

class Shape {
    public: 
    virtual ~Shape() = default;
    virtual void draw() = 0;
};

class Circle : public Shape {
    public:
    void draw() override {
        printf("Circle::draw()\n");
    }
};

class Rectangle : public Shape {
    public:
    void draw() override {
        printf("Rectangle::draw()\n");
    }
};

template<typename To, typename From>     // use like this: down_cast<T*>(foo);
inline To down_cast(From* f)                     
{
  // Ensures that To is a sub-type of From *.  This test is here only
    static_assert(
        std::is_base_of<
            From, 
            typename std::remove_pointer<To>::type    // Extract raw type from To
        >::value,
        "To must be a derived class of From (invalid downcast)."
    );

#if !defined(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI)
  assert(f == NULL || dynamic_cast<To>(f) != NULL);  // RTTI: debug mode only!
#endif
  return static_cast<To>(f);
}

int main() {
    Circle * a = new Circle();
    Shape * b = a;
    b->draw();

    // 
    Circle *c = down_cast<Circle *>(b);
    c->draw();

    Rectangle *d = down_cast<Rectangle *>(b);
    d->draw();

    return 0;
}


If your project already includes the Boost library, we may also use boost::polymorphic_pointer_downcast. its internal implementation is similar to the down_cast we discussed above. 

doc:  polymorphic_downcast
code: polymorphic_cast.hpp