DYNAMIC CLASS Macros

From WxWiki
Jump to navigation Jump to search

Synonyms: DECLARE_DYNAMIC_CLASS(), DECLARE_ABSTRACT_CLASS() and DECLARE_CLASS().

Intent: To support RTTI (Run-Time Type Information) for the class.

Motivation: These macros enable the creation of a class using its name (as a string) and a few more RTTI functionalities.

When to use: Any time you want to be able to dynamically create a class.

Where to use: DECLARE_DYNAMIC_CLASS() should be declared in the private section of your class declaration (.h file), IMPLEMENT_DYNAMIC_CLASS( , ) should be declared before the class implementation (.cpp).

Sample code:

In the .h file:

class WXDLLEXPORT wxListCtrl: public wxControl
{
...
DECLARE_DYNAMIC_CLASS(wxListCtrl)
};

In the .cpp file:

IMPLEMENT_DYNAMIC_CLASS(wxListCtrl, wxControl)
void wxListCtrl::wxListCtrl()
{
}

Note that putting "private:" before DECLARE_DYNAMIC_CLASS is not necessary. The first line of the DECLARE_DYNAMIC_CLASS macro is in fact "public:" so any scope modifiers that come before it are ignored. It is also worth noting that all members that come after a DECLARE_DYNAMIC_CLASS macro will be public!

In order to use these macros, your class must have a default constructor. A semicolon is not required after one of these macros.

DYNAMIC_CLASS macros also make debugging memory leaks easier, as it is possible to get the class name, file, and line number of a leaked class. In order to do this, you need to build the wxWidgets library with all debug flags enabled in setup.h (DEBUG_NEW_ALWAYS and so on). You can also use wxDebugContext to get the number of instances of a certain type if the RTTI-supported class is still outstanding in memory.

See Also

  • RTTI overview
  • IMPLEMENT_DYNAMIC_CLASS2(), IMPLEMENT_ABSTRACT_CLASS(), IMPLEMENT_ABSTRACT_CLASS2(), IMPLEMENT_CLASS() and IMPLEMENT_CLASS2().