Programming with Microsoft Visual C++.NET 6ed [Electronic resources]

George Shepherd, David Kruglinski

نسخه متنی -صفحه : 319/ 289
نمايش فراداده

Dynamic Creation

You've learned that the DECLARE and IMPLEMENT macros add a static CRuntimeClass object to a class. If you use the DECLARE_DYNCREATE or DECLARE-_SERIAL macro (and the corresponding IMPLEMENT macro), you get an additional static member function CreateObject (which is distinct from CRuntimeClass::CreateObject) in your class. Here's an example:

CObject* CMyClass::CreateObject()
{
return new CMyClass;
}

Obviously, CMyClass needs a default constructor. This constructor is declared protected in wizard-generated classes that support dynamic creation.

Now look at the (slightly abbreviated) code for the CRuntime-Class::CreateObject function:

CObject* CRuntimeClass::CreateObject()
{
return (*m_pfnCreateObject)();
}

This function makes an indirect call to the CreateObject function in the target class. Here's how you dynamically construct an object of class CMyClass:

CRuntimeClass* pRTC = RUNTIME_CLASS(CMyObject);
CMyClass* pMyObject = (CMyClass*)pRTC->CreateObject();

Now you know how document templates work. A document template object has three CRuntimeClass* data members initialized at construction to point to the static CRuntimeClass data members for the document, frame, and view classes. When CWinApp::OnFileNew is called, the framework calls the CreateObject functions for the three stored pointers.