MFC › 2. Application Architecture
Runtime Class Information and Dynamic Creation
DECLARE_DYNAMIC, DECLARE_DYNCREATE and IsKindOf.
advanced #mfc#runtime-class#dynamic-create#isKindOf#declare-dynamic#dyncreate#serial#downcast
Explanation
MFC predates standard RTTI (typeid, dynamic_cast) and has its own mechanism, built on a CRuntimeClass object that describes each class. You opt in with macro pairs for classes derived from CObject:
| Declaration (in class) / Implementation (in .cpp) | Gives you |
|---|---|
DECLARE_DYNAMIC / IMPLEMENT_DYNAMIC(Class, Base) |
RUNTIME_CLASS, IsKindOf |
DECLARE_DYNCREATE / IMPLEMENT_DYNCREATE(Class, Base) |
above + create an object by class (CreateObject); needs a default constructor |
DECLARE_SERIAL / IMPLEMENT_SERIAL(Class, Base, schema) |
above + serialization with CArchive (Serialization) |
Operations:
RUNTIME_CLASS(CShape)returns aCRuntimeClass*.obj->IsKindOf(RUNTIME_CLASS(CShape)): is it aCShapeor derived?obj->GetRuntimeClass()->m_lpszClassName: the class name as text.pRC->CreateObject(): anewobject whose type is chosen at run time. This is how document templates create your document, frame and view classes from the class names you register inInitInstance.DYNAMIC_DOWNCAST(CShape, pObj): a checked cast returningnullptron mismatch (the MFCdynamic_cast);STATIC_DOWNCASTasserts in debug builds.
Example
#include <afxwin.h>
#include <iostream>
class CShape : public CObject {
DECLARE_DYNCREATE(CShape)
public:
CShape() {}
virtual double Area() const { return 0; }
};
IMPLEMENT_DYNCREATE(CShape, CObject)
class CCircle : public CShape {
DECLARE_DYNCREATE(CCircle)
public:
CCircle() : m_r(1.0) {}
double Area() const override { return 3.14159 * m_r * m_r; }
private:
double m_r;
};
IMPLEMENT_DYNCREATE(CCircle, CShape)
class CSquare : public CShape {
DECLARE_DYNCREATE(CSquare)
public:
CSquare() : m_s(2.0) {}
double Area() const override { return m_s * m_s; }
private:
double m_s;
};
IMPLEMENT_DYNCREATE(CSquare, CShape)
int _tmain() {
if (!AfxWinInit(::GetModuleHandle(nullptr), nullptr, ::GetCommandLine(), 0)) return 1;
CRuntimeClass* classes[] = { RUNTIME_CLASS(CCircle), RUNTIME_CLASS(CSquare) };
for (CRuntimeClass* pRC : classes) {
CObject* pObj = pRC->CreateObject(); // like "new <class chosen at run time>"
CShape* pShape = DYNAMIC_DOWNCAST(CShape, pObj); // checked cast
std::cout << pRC->m_lpszClassName << ": area " << pShape->Area()
<< ", is a CShape: " << pObj->IsKindOf(RUNTIME_CLASS(CShape)) << "\n";
delete pObj;
}
CCircle circle;
CObject* base = &circle;
std::cout << base->IsKindOf(RUNTIME_CLASS(CCircle)) << base->IsKindOf(RUNTIME_CLASS(CSquare)) << "\n"; // 10
CSquare* wrong = DYNAMIC_DOWNCAST(CSquare, base);
std::cout << (wrong == nullptr) << "\n"; // 1
return 0;
}
Common pitfalls
- The macros come in pairs:
DECLARE_...in the header andIMPLEMENT_...in exactly one.cpp. A missingIMPLEMENT_gives an unresolved-external link error. DECLARE_DYNCREATEneeds a default constructor, and the macro must be placed withpublic:access in mind (it switches access, so put an explicitpublic:after it).- Always name the direct base class correctly in
IMPLEMENT_..., orIsKindOfwalks the wrong chain. - The class must derive from
CObject; plain classes can’t use these macros. IsKindOfis only aboutCObject-derived types registered with the macros; usedynamic_castfor everything else.CreateObjectreturnsCObject*: cast it (withDYNAMIC_DOWNCAST) before use.- MFC’s mechanism does not require
/GR(compiler RTTI);dynamic_castdoes.
Legacy vs modern
Standard C++ (dynamic_cast, typeid) now covers the checking part, and a factory with std::function or a registry map covers creation-by-name. Use the MFC macros where the framework demands them (documents, views, frames, serialization). See RTTI and Casts.
Exercises
1. Why must a document class use DECLARE_DYNCREATE?
The CDocTemplate stores a CRuntimeClass* for the document, frame and view and creates the objects with CreateObject() when the user chooses New or Open.