2

Qt classes have a Q_DECLARE_PRIVATE macro in the public class. The macro reads:

#define Q_DECLARE_PRIVATE(Class)\
    inline Class##Private* d_func() {\
        return reinterpret_cast<Class##Private*>(qGetPtrHelper(d_ptr));\
    }\
    inline const Class##Private d_func() const {\
        return reinterpret_cast<const Class##Private *>(qGetPtrHelper(d_ptr));\
    }\
    friend class Class##Private;

Here, as per my understanding Class##Private will be parent of class of d_ptr then why reinterpret_cast is used and not dynamic_cast?

Sajal
  • 1,783
  • 1
  • 17
  • 21

2 Answers2

4

The reasons are:

  1. A dynamic_cast is not supported in Qt source code, as Qt can be built with RTTI turned off.

    The dynamic_cast< string appears in about a dozen locations in non-tests, non-3rdparty Qt 5.7.0 sources, and most of them are essentially bugs/omissions.

  2. The macro is used in headers where Class##Private is forward-defined. A static_cast wouldn't work as the compiler doesn't know that Class##Private is derived from the pointed-to type of d_ptr.

  3. If Class##Private wasn't forward-defined, then the correct cast to use would be static_cast. A dynamic_cast would be a premature pessimization, since the macro is used in a place where d_ptr's pointed-to type is known at compile time, albeit not in the header.

For more details about Q_DECLARE_PRIVATE, see also How to use the Qt's PIMPL idiom?.

Community
  • 1
  • 1
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
1

Because dynamic_cast requires the class to have at least one virtual method (it needs to be polymorphic). Just class inheritance isn't enough for dynamic_cast to succeed.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
  • The PIMPL classes typically must have a virtual destructor, since they will *always* be destroyed via the pointer to the base class. So that's not it. One big reason is that `dynamic_cast` is not supported in Qt source code. The `dynamic_cast` appears in about a dozen locations in Qt 5.7.0 sources, and all of them are essentially bugs/omissions. – Kuba hasn't forgotten Monica Nov 09 '16 at 20:05