Skip to content
Fix Code Error

Regular cast vs. static_cast vs. dynamic_cast

March 13, 2021 by Code Error
Posted By: Graeme

I’ve been writing C and C++ code for almost twenty years, but there’s one aspect of these languages that I’ve never really understood. I’ve obviously used regular casts i.e.

MyClass *m = (MyClass *)ptr;

all over the place, but there seem to be two other types of casts, and I don’t know the difference. What’s the difference between the following lines of code?

MyClass *m = (MyClass *)ptr;
MyClass *m = static_cast<MyClass *>(ptr);
MyClass *m = dynamic_cast<MyClass *>(ptr);

Solution

static_cast

static_cast is used for cases where you basically want to reverse an implicit conversion, with a few restrictions and additions. static_cast performs no runtime checks. This should be used if you know that you refer to an object of a specific type, and thus a check would be unnecessary. Example:

void func(void *data) {
  // Conversion from MyClass* -> void* is implicit
  MyClass *c = static_cast<MyClass*>(data);
  ...
}

int main() {
  MyClass c;
  start_thread(&func, &c)  // func(&c) will be called
      .join();
}

In this example, you know that you passed a MyClass object, and thus there isn’t any need for a runtime check to ensure this.

dynamic_cast

dynamic_cast is useful when you don’t know what the dynamic type of the object is. It returns a null pointer if the object referred to doesn’t contain the type casted to as a base class (when you cast to a reference, a bad_cast exception is thrown in that case).

if (JumpStm *j = dynamic_cast<JumpStm*>(&stm)) {
  ...
} else if (ExprStm *e = dynamic_cast<ExprStm*>(&stm)) {
  ...
}

You cannot use dynamic_cast if you downcast (cast to a derived class) and the argument type is not polymorphic. For example, the following code is not valid, because Base doesn’t contain any virtual function:

struct Base { };
struct Derived : Base { };
int main() {
  Derived d; Base *b = &d;
  dynamic_cast<Derived*>(b); // Invalid
}

An “up-cast” (cast to the base class) is always valid with both static_cast and dynamic_cast, and also without any cast, as an “up-cast” is an implicit conversion.

Regular Cast

These casts are also called C-style cast. A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering dynamic_cast. Needless to say, this is much more powerful as it combines all of const_cast, static_cast and reinterpret_cast, but it’s also unsafe, because it does not use dynamic_cast.

In addition, C-style casts not only allow you to do this, but they also allow you to safely cast to a private base-class, while the “equivalent” static_cast sequence would give you a compile-time error for that.

Some people prefer C-style casts because of their brevity. I use them for numeric casts only, and use the appropriate C++ casts when user defined types are involved, as they provide stricter checking.

Answered By: Anonymous

Related Articles

  • dynamic_cast and static_cast in C++
  • using reference pointer type as Paramter in c++
  • When should static_cast, dynamic_cast, const_cast…
  • How the int.TryParse actually works
  • What is your most productive shortcut with Vim?
  • How to prevent scrolling the whole page?
  • Why does the function named "traverse" not work on my code?
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Understanding implicit in Scala
  • What are the undocumented features and limitations…
  • Why use static_cast(x) instead of (int)x?
  • Ukkonen's suffix tree algorithm in plain English
  • How does PHP 'foreach' actually work?
  • Efficient Algorithm for Bit Reversal (from…
  • Why are elementwise additions much faster in…
  • Reference - What does this regex mean?
  • What is a NullReferenceException, and how do I fix it?
  • How can I set the aspect ratio in matplotlib?
  • How to sort an array in descending order in Ruby
  • What are the new features in C++17?
  • reversing a string array within a 2D array using…
  • What's the difference between eval, exec, and compile?
  • How to filter a RecyclerView with a SearchView
  • Is it possible to print a variable's type in standard C++?
  • Constant pointer vs Pointer to constant
  • Sort all the elements of the list according to the…
  • C++ cast to derived class
  • SQL query return data from multiple tables
  • How to allocate aligned memory only using the…
  • Why does C++ code for testing the Collatz conjecture…
  • What is an optional value in Swift?
  • What is exactly the base pointer and stack pointer?…
  • What does "Fatal error: Unexpectedly found nil while…
  • data.table vs dplyr: can one do something well the…
  • Finding the type of an object in C++
  • Vue order list view
  • is there a way to write a template function for…
  • Getting started with Haskell
  • iPhone 6 and 6 Plus Media Queries
  • Best practice multi language website
  • When to use reinterpret_cast?
  • What is the incentive for curl to release the…
  • What are type hints in Python 3.5?
  • Memcached vs. Redis?
  • Vue&TypeScript: how to avoid error TS2345 when…
  • "Thinking in AngularJS" if I have a jQuery background?
  • Extract from Union type where discriminator is also a Union
  • Understanding group and or in regular expression
  • For-each over an array in JavaScript
  • Calculate time difference in minutes in SQL Server
  • What's the difference between utf8_general_ci and…
  • How to increment a pointer address and pointer's value?
  • Creating a list of single type of objects
  • What's the best way of scraping data from a website?
  • Where and why do I have to put the "template" and…
  • is deleting a variable allocated in heap using void…
  • Java Class.cast() vs. cast operator
  • How to paste yanked text into the Vim command line
  • Creating a singleton in Python
  • Correct format specifier to print pointer or address?
  • c++ useless-cast from size_t to uint32_t for…
  • How do I use data from Vue.js child component within…
  • ExpressJS How to structure an application?
  • Can't resolve the implicit for a constrained class…
  • In CSS Flexbox, why are there no "justify-items" and…
  • Programmatically Lighten or Darken a hex color (or…
  • Usage of __slots__?
  • Save foreign key to other Model with hasMany relation
  • Reference — What does this symbol mean in PHP?
  • What does T&& (double ampersand) mean in C++11?
  • C++ template,typename and operator
  • Vue.JS "TypeError: reverseMessage is not a function"
  • Logging best practices
  • Java 8: Difference between two LocalDateTime in…
  • Conversion failed when converting the varchar value…
  • What is a smart pointer and when should I use one?
  • commandButton/commandLink/ajax action/listener…
  • How to generate a random string of a fixed length in Go?
  • Correctly Parsing JSON in Swift 3
  • Identifying and solving…
  • Directly assigning values to C Pointers
  • Replacing a 32-bit loop counter with 64-bit…
  • How to place object files in separate subdirectory
  • What does a "Cannot find symbol" or "Cannot resolve…
  • How to use Servlets and Ajax?
  • Database development mistakes made by application developers
  • How to make a SIMPLE C++ Makefile
  • Smart way to truncate long strings
  • What does "dereferencing" a pointer mean?
  • How can I extract embedded fonts from a PDF as valid…
  • C++ How to make a function overload that accepts…
  • Imshow: extent and aspect
  • Why do git fetch origin and git fetch : behave differently?
  • What is the copy-and-swap idiom?
  • Python timedelta in years
  • How is possible to read different output from same…
  • Examples of GoF Design Patterns in Java's core libraries
  • Using pointer to char array, values in that array…
  • Is this request generated by EF Core buggy or is it my code?
  • Understanding PrimeFaces process/update and JSF…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Click through div to underlying elements

Next Post:

Array to String PHP?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error