Why use static_cast(x) instead of (T)x?

The main reason is that classic C casts make no distinction between what we call static_cast<>(), reinterpret_cast<>(), const_cast<>(), and dynamic_cast<>(). These four things are completely different. A static_cast<>() is usually safe. There is a valid conversion in the language, or an appropriate constructor that makes it possible. The only time it’s a bit risky is … Read more

How does qobject_cast work?

This is a little complicated… Remember that qobject_cast<T>(obj) is a way to dynamically cast a QObject to the target type T which also derives from QObject. Now, for this to work, the macro Q_OBJECT should be included in the definition of class T. Apparently, the qt_check_for_QOBJECT_macro call is for checking that the class really contains … Read more

Why do we have reinterpret_cast in C++ when two chained static_cast can do its job?

There are things that reinterpret_cast can do that no sequence of static_casts can do (all from C++03 5.2.10): A pointer can be explicitly converted to any integral type large enough to hold it. A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer to a function can be … Read more

Should I use static_cast or reinterpret_cast when casting a void* to whatever

Use static_cast: it is the narrowest cast that exactly describes what conversion is made here. There’s a misconception that using reinterpret_cast would be a better match because it means “completely ignore type safety and just cast from A to B”. However, this doesn’t actually describe the effect of a reinterpret_cast. Rather, reinterpret_cast has a number of … Read more

Why can’t I static_cast between char * and unsigned char *?

They are completely different types see standard: 3.9.1 Fundamental types [basic.fundamental] 1 Objects declared as characters char) shall be large enough to store any member of the implementation’s basic character set. If a character from this set is stored in a character object, the integral value of that character object is equal to the value … Read more

Proper way of casting pointer types

For convertible pointers to fundamental types both casts have the same meaning; so you are correct that static_cast is okay. When converting between some pointer types, it’s possible that the specific memory address held in the pointer needs to change. That’s where the two casts differ. static_cast will make the appropriate adjustment. reinterpret_cast will not. … Read more

C++ cannot convert from base A to derived type B via virtual base A

In order to understand the cast system, you need to dive into the object model. The classic representation of a simple hierarchy model is containment: if B derives from A then the B object will, in fact, contain an A subobject alongside its own attributes. With this model downcasting is a simple pointer manipulation by … Read more

tech